text:
from abc import ABCMeta
from collections.abc import Iterable
import copy
from enum import Enum
import json
import logging
import os
import sys

from nativeconfig.exceptions import ValidationError, DeserializationError

LOG = logging.getLogger('nativeconfig')

class ValueSource(Enum):
    resolver = 1
    default = 2
    config = 3
    one_shot = 4
    env = 5

class BaseOption(property, metaclass=ABCMeta):
    """
    Base class for all options.

    Value of each option can be represented by three different versions:

        1. Python Value: used in the code
        2. Raw Value (UTF-8 sting): used to store in underlying config
        3. JSON Value: used to interact with the user

    Value of an option can be overridden by an environment variable.

    Setting option to None is equivalent to deleting it.

    @raise ValueError: Raise if any of the arguments has inappropriate value.
    @raise ValidationError: Raise if default value or any of the choices values is invalid.
    """
    def __init__(self,
                 name,
                 *,
                 getter='get_value',
                 setter='set_value',
                 deleter='del_value',
                 resolver='resolve_value',
                 choices=None,
                 env_name=None,
                 default=None,
                 allow_cache=None,
                 doc=None):
        """
        @param name: Name of the property.
        @type name: str

        @param getter: Name of the method of the enclosing class to get value.

        @param setter: Name of the of the enclosing class to set value.

        @param deleter: Name of the deleter of the enclosing class to delete value.

        @param resolver: Name of the resolver of the enclosing class to resolve value that cannot be serialized.

        @param choices: List of allowed Python Values for the option. Deep copied.
        @type choices: Container

        @param env_name: Name of the env variable that contains JSON Value that can override value of the option.
        @type env_name: str

        @param default: Default Python Value of the option. Deep copied.

        @param allow_cache: Whether value can be cached. If None, default of enclosing config will be used.
        @type allow_cache: bool

        @raise ValueError: If any of arguments is incorrect. Only handles most obvious errors.
        @raise ValidationError: If default or any of choices is invalid.
        """
        super(BaseOption, self).__init__(self.fget, self.fset, self.fdel, doc=doc or self.__doc__)

        self._name = name
        self._getter = getter
        self._setter = setter
        self._deleter = deleter
        self._resolver = resolver
        self._choices = copy.deepcopy(choices) if choices is not None else None
        self._env_name = env_name
        self._default = copy.deepcopy(default) if default is not None else None
        self._allow_cache = allow_cache
        self.__doc__ = doc or self.__doc__

        self._one_shot_value = None
        self._is_one_shot_value_set = False  # None is allowed for One Shot Value

        if not isinstance(name, str) or not name:
            raise ValueError("'name' must be nonempty string")

        if env_name is not None and (not isinstance(env_name, str) or not env_name):
            raise ValueError("'env_name' must be nonempty string")

        if choices is not None and (not isinstance(choices, Iterable) or not choices):
            raise ValueError("'choices' must be nonempty iterable")

        if choices is not None:
            for c in choices:
                self.validate(c)

        if default is not None:
            self.validate(default)

    @property
    def name(self):
        return self._name

    @property
    def choices(self):
        return copy.deepcopy(self._choices)

    @property
    def default(self):
        return copy.deepcopy(self._default)

    def set_one_shot_value(self, python_value):
        """
        Set One Shot Value of the option that overrides Raw Value from storage but can be reset by set.

        Useful if you want to allow a user to temporary override the option via CLI.

        @raise ValidationError: Raise if python_value is not valid.
        """
        if python_value is not None:
            self.validate(python_value)
        self._one_shot_value = python_value
        self._is_one_shot_value_set = True

    #{ Validation

    def validate(self, python_value):
        """
        Validate Python Value. Must raise ValidationError if value is wrong.

        @raise ValidationError: Raise if value is wrong.
        """
        if python_value is None:
            raise ValidationError("None is never valid and must not reach this method", python_value, self.name)

        if self._choices is not None and python_value not in self._choices:
            raise ValidationError("'{}' must be in {}".format(python_value, self._choices), python_value, self.name)

    #{ Serialization and deserialization

    def serialize(self, python_value):
        """
        Serialize Python Value into Raw Value.

        @see: deserialize

        @raise SerializationError: Raise if value cannot be serialized.
        """
        return str(python_value)

    def deserialize(self, raw_value):
        """
        Deserialize Raw Value into Python Value.

        @see: serialize

        @raise DeserializationError: Raise if value cannot be deserialized.
        """
        return str(raw_value)

    def serialize_json(self, python_value):
        """
        Serialize Python Value into JSON Value.

        Custom implementation should properly handle None as a python_value.

        @see: deserialize_json

        @rtype: str
        """
        return json.dumps(python_value)

    def deserialize_json(self, json_value):
        """
        Deserialize JSON Value into Python Value.

        Custom implementation should properly handle None as a python_value.

        @see: serialize_json
        """
        try:
            return json.loads(json_value)
        except ValueError:
            raise DeserializationError("'{}' is invalid JSON".format(json_value), json_value, self.name)

    #{ Access backend

    def allow_cache(self, enclosing_self):
        return self._allow_cache or \
               (self._allow_cache is None and hasattr(enclosing_self, 'ALLOW_CACHE') and enclosing_self.ALLOW_CACHE)

    def read_value(self, enclosing_self):
        """
        Read value for the option from all supported sources.

        @param enclosing_self: Instance of class that defines this property.

        @rtype: (object, ValueSource)
        """
        def make_python_value_from_json_value(json_value, source):
            try:
                python_value = self.deserialize_json(json_value)
                self.validate(python_value)
                return python_value, source
            except (DeserializationError, ValidationError):
                return getattr(enclosing_self, self._resolver)(sys.exc_info(), self.name, json_value, source), ValueSource.resolver

        def make_python_value_from_raw_value(raw_value, source):
            try:
                python_value = self.deserialize(raw_value)
                self.validate(python_value)
                return python_value, source
            except (DeserializationError, ValidationError):
                return getattr(enclosing_self, self._resolver)(sys.exc_info(), self.name, raw_value, source), ValueSource.resolver

        python_value, source = None, None

        if self._env_name:
            json_value = os.getenv(self._env_name)
            if json_value == 'null':
                LOG.debug('Value of \"%s\" is reset to default by environment variable.', self.name)
                python_value, source = self._default, ValueSource.env
            elif json_value is not None:
                LOG.debug("Value of \"%s\" is overridden by environment variable: %s.", self.name, json_value)
                python_value, source = make_python_value_from_json_value(json_value, ValueSource.env)

        if python_value is None and self._is_one_shot_value_set:
            LOG.debug("Value of \"%s\" is temporary overridden by one shot value: %s.", self.name, self._one_shot_value)
            python_value, source = self._one_shot_value, ValueSource.one_shot
        elif python_value is None:
            raw_value = getattr(enclosing_self, self._getter)(self.name, allow_cache=self.allow_cache(enclosing_self))
            if raw_value is not None:
                python_value, source = make_python_value_from_raw_value(raw_value, ValueSource.config)

        if python_value is None:
            LOG.debug("No value is set for \"%s\", use default.", self.name)
            python_value, source = self._default, ValueSource.default

        return python_value, source

    def fget(self, enclosing_self):
        """
        Read Raw Value from the storage and deserialize it into Python Value.

        If either DeserializationError or ValidationError occurs in process, they will be forwarded to resolver.

        @param enclosing_self: Instance of class that defines this property.
        """
        return self.read_value(enclosing_self)[0]

    def fset(self, enclosing_self, python_value):
        """
        Serialize Python Value into Raw Value and write it to storage.

        Resets One Shot Value.
        Setting None simply deletes Raw Value from storage.

        @param enclosing_self: Instance of class that defines this property.

        @param python_value: Python Value to be set.
        """
        self._one_shot_value = None
        self._is_one_shot_value_set = False

        if python_value is not None:
            self.validate(python_value)
            raw_value = self.serialize(python_value)
            getattr(enclosing_self, self._setter)(self.name, raw_value, allow_cache=self.allow_cache(enclosing_self))
        else:
            self.fdel(enclosing_self)

    def fdel(self, enclosing_self):
        """
        Delete Raw Value from the config.

        @param enclosing_self: Instance of class that defines this property.
        """
        self._one_shot_value = None
        self._is_one_shot_value_set = False
        getattr(enclosing_self, self._deleter)(self.name, allow_cache=self.allow_cache(enclosing_self))

    #}

class BaseContainerOption(BaseOption):
    """
    Base class for container options.

    A container option is an option that consists of other options.
    Think of it as of typed container, where each element is an option of a given type.

    Unlike BaseOption, raw values are represented by a container class (such as list or dict) where each value
    is a UTF-8 encoded string.
    """
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)


text:
% Scripted example of Numerical Optimization of gradient Waveforms (NOW)
clear

% Change the parameters below to your liking. Those not
% specified are default-initialized as follows (see optimizationProblem for details):
%    Max gradient = 80 milliTesla/m
%    Max slew rate = 100 milliTesla/m/milliSecond = 100 T/m/s
%    Eta (heat dissipation parameter) = 1
%    Discretization points = 77
%    Target tensor = eye(3)
%    Initialguess = 'random'
%    zeroGradientAtIndex = [], i.e. only at start and end
%    enforceSymmetry = false;
%    redoIfFailed = true;
%    useMaxNorm = false;
%    doMaxwellComp = true;
%    MaxwellIndex = 100;
%    Motion compensation: disabled
%    Background compensation: disabled
%
% Written by Jens Sjölund and Filip Szczepankiewicz

%%  PREP
% First, set up the optimization problem. Do this first to create a
% structure where fields are pre-specified. Note that some fields are
% read-only and that new fields cannot be created.
problem = optimizationProblem;

% Define the hardware specifications of the gradient system
problem.gMax =  80; % Maximal gradient amplitude, in [mT/m]
problem.sMax = 100; % Maximal gradient slew (per axis), in [T/(sm)]

% Request encoding and pause times based on sequence timing in [ms]
problem.durationFirstPartRequested    = 32;
problem.durationSecondPartRequested   = 27;
problem.durationZeroGradientRequested = 8;

% Define the b-tensor shape in arbitrary units. This example uses an
% isotropic b-tensor that results in spherical tensor encoding (STE).
problem.targetTensor = eye(3);

% Define the number of sample points in time. More points take longer to
% optimize but provide a smoother waveform that can have steeper slopes.
problem.N = 50;

% Set the balance between energy consumption and efficacy
problem.eta = 0.9; %In interval (0,1]

% Set the threshold for concomitant gradients (Maxwell terms).
% Please see https://doi.org/10.1002/mrm.27828 for more information on how
% to set this parameter.
problem.MaxwellIndex = 100; %In units of (mT/m)^2 ms

% Set the desired orders of motion compensation and corresponding
% thresholds for allowed deviations. See Szczepankiewicz et al., MRM, 2020
% for details. maxMagnitude in units s^order / m.
problem.motionCompensation.order = [1, 2];
problem.motionCompensation.maxMagnitude = [0, 1e-4];

% Toggle compensation for background gradients
problem.doBackgroundCompensation = true;

% Make a new optimizationProblem object using the updated specifications.
% This explicit call is necessary to update all private variables.
problem = optimizationProblem(problem);

%% PRINT REQUESTED AND TRUE TIMES
% Note that due to the coarse raster, the requested and actual times may
% differ slightly.
clc
now_print_requested_and_real_times(problem);

%% RUN OPTIMIZATION
[result, problem] = NOW_RUN(problem);

%% PLOT RESULT
plot(0:problem.dt:problem.totalTimeActual,result.g)
xlabel('Time [ms]')
ylabel('Gradient amplitude [mT/m]')
measurementTensor = result.B

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Responsive Carousel Demo Page</title>

  <link rel="stylesheet" href="../../src/responsive-carousel.css" media="screen">
  <link rel="stylesheet" href="../../src/responsive-carousel.slide.css" media="screen">
  <link rel="stylesheet" href="../assets/demostyles.css">


text:
//
//  TCVerb.h
//  RSTCAPI
//
//  Created by Brian Rogers on 3/3/13.

#import <Foundation/Foundation.h>
#import "TCLocalizedValues.h"

@interface TCVerb : NSObject

- (id) initWithId:(NSString *)verbId withVerbDisplay:(TCLocalizedValues *)display;
- (id) initWithJSON:(NSString *)verbJSON;
- (id) initWithDictionary:(NSDictionary *)verbDictionary;
- (NSDictionary *)dictionary;
- (NSString *) JSONString;
@end


text:
namespace $.$$ {
	export class $mol_plot_mark_hor extends $.$mol_plot_mark_hor {
		@ $mol_mem
		series_x(): readonly number[] {
			return this.labels().map((val, index) => index)
		}

		@ $mol_mem
		labels() {
			return this.series_x().map(val => String(val)) as readonly string[]
		}

		@ $mol_mem
		visible_indexes() {
			const series_x = this.series_x()
			const labels = this.labels()
			const [shift_x,] = this.shift()
			const [scale_x,] = this.scale()
			let step = this.step() * scale_x
			const [[viewport_left, viewport_right]] = this.viewport()
			const size_x = viewport_right - viewport_left
			const font_size = this.font_size()
			let indexes: number[]
			let labels_width: number
			do {
				indexes = []
				labels_width = 0
				let last: number = 0
				let current = 0
				for (let i = 0; i < series_x.length; i++) {
					const point_x = series_x[i]
					const scaled_x = (shift_x + point_x * scale_x)
					if (scaled_x < viewport_left) continue
					if (scaled_x > viewport_right) continue
					if (current === 0) current = scaled_x
					if (scaled_x < current) {
						last = i
						continue
					}
					indexes.push(i)
					current += step
					last = 0
					labels_width += font_size * (labels[i].length + 1)
					if (labels_width > size_x) break
				}
				if (last !== 0) {
					indexes.push(last)
					labels_width += font_size * (labels[last].length + 1)
				}

				step *= 1.5
			} while (labels_width > size_x && indexes.length > 2)

			return indexes

		}

		curve() {
			const [shift] = this.shift()
			const [scale] = this.scale()
			const series_x = this.series_x()

			return this.visible_indexes().map( index => {
				const scaled = series_x[index] * scale + shift
				return `M ${ scaled.toFixed(3) } 1000 V 0`
			}).join( ' ' )
		}

		label_text( index : number ) {
			return this.labels()[index]
		}

		labels_formatted() {
			return this.visible_indexes().map( index => this.Label( index ) )
		}

		label_pos_x( index : number ) {
			return (this.series_x()[index] * this.scale()[0] + this.shift()[0]).toFixed(3)
		}

		label_pos_y( index : number ) {
			return this.title_pos_y()
		}
	}
}


text:
<?xml version="1.0"?>
<!DOCTYPE Configure PUBLIC "-//Jetty//Configure//EN" "http://www.eclipse.org/jetty/configure_9_3.dtd">

<!-- =============================================================== -->
<!-- Mixin the Statistics Handler                                    -->
<!-- =============================================================== -->

<Configure id="Server" class="org.eclipse.jetty.server.Server">
  <Call name="insertHandler">
    <Arg>
      <New id="StatsHandler" class="org.eclipse.jetty.server.handler.StatisticsHandler">
      </New>
    </Arg>
  </Call>
  <Call class="org.eclipse.jetty.server.ServerConnectionStatistics" name="addToAllConnectors">
    <Arg><Ref refid="Server"/></Arg>
  </Call>
</Configure>


text:
package com.payneteasy.superfly.security.filters.internal;

import com.github.mustachejava.DefaultMustacheFactory;
import com.github.mustachejava.Mustache;
import com.github.mustachejava.MustacheFactory;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

public class MustachePrinter {

    Mustache mustache;
    Map<String, Object> scope = new HashMap<>();

    public MustachePrinter(String aTemplate) {
        MustacheFactory mf = new DefaultMustacheFactory();
        mustache = mf.compile(aTemplate);
    }

    public void add(String aName, Object aValue) {
        scope.put(aName, aValue);
    }

    public void write(PrintWriter aWriter) throws IOException {
        mustache.execute(aWriter, scope).flush();
    }

}


text:
#ifndef _DEV_NPLULED_H_
#define _DEV_NPLULED_H_

/*!
 * \file dev/npluled.h
 * \brief Low Level User LED (Green) Access.
 *
 * Low level User LED (Green) hardware routines for the programmable logic provided
 * on the Ethernut 3 reference design.
 **
 * \verbatim
 **
 * Revision 1.0  2006/01/22 10:01:02  alex (k.vassliev)
 * First check-in.
 *
 *
 * \endverbatim
 */

#include "npl.h"

/*!
 * \addtogroup xgNpl
 */
/*@{*/

/*!
 * \brief ULED status definitions
 *
 */
#define ULED_ON     1
#define ULED_OFF    0

/* Function prototypes. */
extern void NplUledCntl(int status);
extern int NplUledStatus(void);
/* */
/*@}*/
#endif


text:
<?php

defined('_JEXEC') or die;

$doc = JFactory::getDocument();

// Add Stylesheets
JHtml::_('bootstrap.loadCss', true, $this->direction);
JHtml::_('stylesheet', 'installation/template/css/template.css');

// Load the JavaScript behaviors
JHtml::_('bootstrap.framework');
JHtml::_('formbehavior.chosen', 'select');
JHtml::_('behavior.framework', true);
JHtml::_('behavior.keepalive');
JHtml::_('behavior.formvalidation');
JHtml::_('script', 'installation/template/js/installation.js');

// Load the JavaScript translated messages
JText::script('INSTL_PROCESS_BUSY');
JText::script('INSTL_FTP_SETTINGS_CORRECT');
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="<?php echo $this->language; ?>" lang="<?php echo $this->language; ?>" dir="<?php echo $this->direction; ?>">

		<jdoc:include type="head" />

			<img src="<?php echo $this->baseurl ?>/template/images/joomla.png" alt="Joomla" />

				<?php
				$joomla = 'Joomla!®';
				$license = '' . JText::_('INSTL_GNU_GPL_LICENSE') . '';
				echo JText::sprintf('JGLOBAL_ISFREESOFTWARE', $joomla, $license);
				?>

			<jdoc:include type="message" />

						<?php echo JText::_('INSTL_WARNJAVASCRIPT'); ?>

				<jdoc:include type="component" />


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

  <title>Module: Systems::Syncing</title>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <meta http-equiv="Content-Script-Type" content="text/javascript" />
  <link rel="stylesheet" href="../.././rdoc-style.css" type="text/css" media="screen" />

          Module
          Systems::Syncing

            In:

                lib/systems/syncing.rb

Methods

      deactivate_admin_responses
      update_cache

Public Instance methods

          deactivate_admin_responses()

[Source]

    # File lib/systems/syncing.rb, line 3
 3:     def deactivate_admin_responses
 4:       response_ids = Response.all(
 5:         :select => 'responses.id',
 6:         :joins => "INNER JOIN visits ON responses.visit_id=visits.id INNER JOIN users ON (visits.user_id=users.id AND users.state LIKE 'admin')",
 7:         :conditions => "active=1 AND users.state LIKE 'admin'",
 8:         :group => 'responses.id'
 9:       ).map(&:id)
10:       Response.update_all("active=0", "responses.active=1 AND responses.id IN (#{response_ids.join(',')})") unless response_ids.empty?
11:       response_ids
12:     end

          update_cache()

[Source]

    # File lib/systems/syncing.rb, line 14
14:     def update_cache
15:       ItemsQuestion.transaction do
16:         ItemsQuestion.all(:include => :item).each do |iq|
17:           next if iq.item.nil?
18:           wins = iq.item.wins(iq.question_id, '')
19:           ratings = iq.item.ratings(iq.question_id)
20:           losses = ratings - wins
21:           iq.update_attributes(:wins => wins, :ratings => ratings, :losses => losses)
22:         end
23:       end
24:     end

[Validate]


text:
node_socket.io_room_redis_store
===============================

Sample app in Node using Socket.io rooms with redis store


text:
user-profile-sync,  sync browser profiles to tmpfs.
==================================================

|                |                                                     |
|----------------|-----------------------------------------------------|
| Homepage:      |  https://github.com/GutenYe/user-profile-sync       |
| Author:	       | Guten                                               |
| License:       | MIT-LICENSE                                         |
| Issue Tracker: | https://github.com/GutenYe/user-profile-sync/issues |

Since the profile(s), browser cache, etc. are relocated into tmpfs, the corresponding onslaught of I/O associated with using the browser is also redirected from the physical disc to RAM, thus reducing wear to the physical disc and also greatly improving browser speed and responsiveness. The access time of RAM is on the order of nanoseconds while the access time of physical discs is on the order of milliseconds. This is a difference of six orders of magnitude or 1,000,000 times faster.

**Support Browsers**: firefox, chromium, opera, midori

It based on [user-daemon-system](https://github.com/GutenYe/user-daemon-system).

Install
-------

	$ yaourt -S user-profile-sync-daemon-git

Chromium actually keeps its cache directory separate from its browser profile directory.

	$ chromium --disk-cache-dir=/tmp/cache/chromium/Default  # for Default profile

Sync all profiles every ten minutes.

	$ crontab -e   # optional
		*/10 * * * *  ~/etc/rc.d/profile-sync sync &> /dev/null

Put it into hibernate and suspend

	# /etc/pm/sleep.d/20-profile-sync.conf
		case $1 in
				hibernate|suspend) su <user> -c '~/etc/rc.d/profile-sync sync' ;;
		esac

see https://wiki.archlinux.org/index.php/Pm-utils#Creating_your_own_hooks

Note on Patches/Pull Requests
-----------------------------

1. Fork the project.
2. Make your feature addition or bug fix.
3. Add tests for it. This is important so I don't break it in a future version unintentionally.
4. Commit, do not mess with rakefile, version, or history. (if you want to have your own version, that is fine but bump version in a commit by itself I can ignore when I pull)
5. Send me a pull request. Bonus points for topic branches.

Credits
-------

* profile-sync-daemon by graysky
* [Contributors](https://github.com/GutenYe/user-profile-sync/contributors)

Resources
--------

* [Firefox Ramdisk](https://wiki.archlinux.org/index.php/Firefox_Ramdisk)
* [Chromium Cache in tmpfs](https://wiki.archlinux.org/index.php/Chromium_Tips_and_Tweaks#Cache_in_tmpfs)
* [profile-sync-daemon](https://bbs.archlinux.org/viewtopic.php?pid=1026974): sync brower profiles to tmpfs.
* [user-daemon-system](https://github.com/GutenYe/user-daemon-system): The missing daemon system for user.

Copyright
---------

(the MIT License)

Copyright (c) 2011-2012 Guten

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:paddingLeft="2.5dp"
    android:paddingBottom="2.5dp"
    android:paddingRight="2.5dp"
    android:paddingTop="2.5dp"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <RelativeLayout
        android:layout_width="match_parent"
        android:id="@+id/layout_grid"
        android:layout_below="@+id/total_results"
        android:layout_above="@+id/footer"
        android:layout_height="wrap_content">
        <GridView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/blogs"
            android:horizontalSpacing="0dp"
            android:verticalSpacing="0dp"
            android:stretchMode="columnWidth"
            android:rowCount="2"
            android:scrollbarSize="0dp"
            android:columnWidth="100dp"
            android:gravity="center"
            android:layout_centerHorizontal="true" />
    </RelativeLayout>
</LinearLayout>


text:
.. pyapi-gitlab documentation master file, created by
   sphinx-quickstart on Sun Aug 04 20:46:27 2013.
   You can adapt this file completely to your liking, but it should at least
   contain the root `toctree` directive.

Welcome to pyapi-gitlab's documentation!
=========================================

pyapi-gitlab is a wrapper to access all the functions of Gitlab from our python scripts.

How to use it
==================

There are several optional parameters in a lot of the commands, you should check the command documentation or the
command string, for example adding an user accepts up to 7 extra parameters.

First we import our library::

   import gitlab

Then we need to authenticate to our Gitlab instance. There is 3 ways of doing this.

Authenticating via user/password
==================================

First create the instance passing the gitlab server as parameter::

   git = gitlab.Gitlab("our_gitlab_host")

Then call the login() method::

   git.login("user", "password")

That's it, now your gitlab instance is using the private token in all the calls. You can see it in the token variable

Authenticating via private_token
====================================

You can also authenticate via the private_token that you can get from your gitlab profile and it's easier than using user/password

Just call the instance with the parameter token::

    git = gitlab.Gitlab("our_gitlab_host", token="mytoken")

Authenticating via oAuth2 token
====================================

You can also authenticate via the oAuth token that you can get from your gitlab profile and it's easier than using user/password

Just call the instance with the parameter oauth_token::

    git = gitlab.Gitlab("our_gitlab_host", oauth_token="mytoken")

Using sudo on the functions
=============================

All API calls support using sudo (e.g. calling the API as a different user)
This is accomplished by using the setsudo() method to temporarily make all requests as another user, then calling it with no args to go back to the original user::

    >>> git = gitlab.Gitlab(host=host)
    >>> git.login(user=user, password=password)
    True
    >>> git.currentuser()["username"]
    u'root'
    >>> [[u["id"], u["username"]] for u in git.getusers()]
    [[1, u'root'], [9, u'sudo_user'], [10, u'NMFUQ85Y']]
    >>> # lets try with sudo_user
    >>> git.setsudo(9)
    >>> git.currentuser()["username"]
    u'sudo_user'
    >>> # lets change back to the original user
    >>> git.setsudo(1)
    >>> git.currentuser()["username"]
    u'root'

Pagination
===========

All get* functions now accept a page and per_page parameter::

    git.getissues(page=1, per_page=40)

The default is to get page 1 and 20 results per page. The max value for per_page is 100.

Getting all results
====================

There is a getall method which will return all results for any call that accepts pagination::

    git.getall(git.getprojects)

Used in loops::

    for project in git.getall(git.getprojects):
        pass

Treated as a generator::

    print ", ".join(user['username'] for user in git.getall(git.getusers, per_page=100))

Wrap with list() which retrieves all the elements::

    print 'number of users: %d' % len(list(git.getall(git.getusers)))

Start from any page::

    # skip the first 4400 results
    len(list(git.getall(git.getusers, page=51, per_page=80)))

And with positional args::

    print len(list(git.getall(git.getgroupmembers, 191, page=3, per_page=7)))

API doc
==================

Every method now has the documentation as a docstring.
The best way of checking what the API entails is to go to the Gitlab API page directly as this library is a 1:1 translation of it.
http://doc.gitlab.com/ce/api/README.html

.. automodule:: gitlab

.. autoclass:: Gitlab
    :members:

Indices and tables
==================

* :ref:`genindex`
* :ref:`search`


text:
About
=====

This is a ctypes based python wrapper for snap7. Snap7 is an open source,
32/64 bit, multi-platform Ethernet communication suite for interfacing natively
with Siemens S7 PLCs.

python-snap7 support Python 2.7 and 3.4, Windows Linux and OS X.

.. image:: https://travis-ci.org/gijzelaerr/python-snap7.png?branch=master
  :target: https://travis-ci.org/gijzelaerr/python-snap7

.. image:: https://badges.gitter.im/gijzelaerr/python-snap7.png
  :target: https://gitter.im/gijzelaerr/python-snap7

The full documentation is available on `Read The Docs <http://python-snap7.readthedocs.org/en/latest/>`_.

see `python-snap7 in action <http://youtu.be/G-Gj_r2BQBk/>`_.

Installation
============

Please read the
`online installation documentation <http://python-snap7.readthedocs.org/en/latest/installation.html>`_.

credits
=======

- Gijs Molenaar
- Stephan Preeker.  *I'm available for consulting work to help you do integration with siemens PLC's. stephan at preeker dot net*

Special thanks to
=================

- Davide Nardella for creating snap7
- Thomas Hergenhahn for his libnodave.
- Thomas W for his S7comm wireshark plugin


text:
import requests
import os
import json

from helpers.dbutils import CloudantDbUtils
import conftest

# get the cloudant credentials from pytest config file
test_properties = conftest.test_properties()

class DataLoader:
	"""
	Test data loader related functions
	"""

	def getInputJsonFilepath(self, db_name):
		return os.path.join("resources", "schema_data", "{}.json".format(db_name))

	def loadData(self):
		cloudantUtils = CloudantDbUtils(test_properties)
		for db in cloudantUtils.test_dbs:
			inputJsonFilePath = self.getInputJsonFilepath(db)
			if os.path.exists(inputJsonFilePath):
					if cloudantUtils.db_exists(db):
						with open(inputJsonFilePath, "r") as fh:
							bulkDocsJson = json.loads(fh.read())
							if cloudantUtils.bulk_insert(db, json.dumps(bulkDocsJson)):
								print("Successfully inserted the docs into {} from ./{}".format(db, inputJsonFilePath))
							else:
								print("Failed to insert the docs into {}".format(db))
					else:
						print("{} doesn't exist".format(db))

if  __name__ =='__main__':
	"""
	Utility for python spark-cloudant schema tests
	"""
	import argparse
	parser = argparse.ArgumentParser(description="Utility for python spark-cloudant schema tests")
	group = parser.add_mutually_exclusive_group(required=True)
	group.add_argument('-addDocs', action='store_true', help='Add required docs for spark-cloudant schema tests')

	args = parser.parse_args()

	dataloader = DataLoader()

	if args.addDocs:
		dataloader.loadData()


text:
Getting a model projected onto the screen using WebGL is only the first step for working in 3d. The next is applying a shading or lighting model to it. This content kit walks through the steps on how to build the classic Lambertian lighting model and the Blinn Phong lighting model.

Lesson                  | JSFiddle                                                 | Code                                                    | Time Estimation |
----------------------- | ---------------------------------------------------------| ---------------------------------------------------------------- | ------ |
No Lighting             | TODO                                                     | [01-no-lighting](lessons/01-no-lighting)                         | 15 min |
Normal Lighting         | TODO                                                     | [02-normal-lighting](lessons/02-normal-lighting)                 | 15 min |
Transform Normals       | TODO                                                     | [03-transform-normals](lessons/03-transform-normals)             | 15 min |
Lambert Lighting        | TODO                                                     | [04-lambert-lighting](lessons/04-lambert-lighting)               | 20 min |
Blinn Phong Lighting    | TODO                                                     | [05-blinn-phong-lighting](lessons/05-blinn-phong-lighting)       | 20 min |

## Getting started (10 min)

The lessons can either be worked online from JSFiddle, or downloaded and explored locally. The content of the lessons is mixed in with the code. The `script.js` files contain most of the lesson, while the `index.html` contains the HTML and shader code. To download these files either [grab the zip file](https://github.com/TatumCreative/mdn-lighting-models/archive/master.zip) or run `git clone git@github.com:TatumCreative/mdn-lighting-models.git` from the command line.

#### Working locally checklist

 1. Verify that [WebGL works on your machine](https://get.webgl.org/).
 2. Download the lesson files to your machine.
 3. Open the lessons in the browser:
   * Either open the index.html files from the lessons in your browser
   * Or if you are serving files with a local webserver, make sure and serve them from the root directory of the content kit so that the shared js files can be correctly loaded in.

#### Working on JSFiddle checklist

 1. Verify that [WebGL works on your machine](https://get.webgl.org/).
 2. Visit the JSFiddle links

## Lesson requirements

These lessons require a [browser and device that support WebGL](https://get.webgl.org/). The browsers that support these features are Firefox 4+, Google Chrome 9+, Opera 12+, Safari 5.1+ and Internet Explorer 11+. Be aware that not all devices support WebGL even if the browsers do. There are many tutorials available throughout the web on graphics programming, but this content kit specifically targets web developers. It's assumed that the audience is familiar with an intermediate level web development, markup, and JavaScript.

## Updates and Correction

[Submit an issue](./issues) or a [pull request](https://help.github.com/articles/using-pull-requests/) for any corrections or updates. For a history of the updates visit the [commit history](https://github.com/TatumCreative/mdn-lighting-models/commits/master).


text:
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_PUBSUB_INTERNAL_SUBSCRIBER_STUB_FACTORY_H
#define GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_PUBSUB_INTERNAL_SUBSCRIBER_STUB_FACTORY_H

#include "google/cloud/pubsub/internal/subscriber_stub.h"
#include "google/cloud/options.h"
#include <memory>

namespace google {
namespace cloud {
namespace pubsub_internal {
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN

/// Create a SubscriberStub using a pre-configured channel.
std::shared_ptr<SubscriberStub> CreateDefaultSubscriberStub(
    std::shared_ptr<grpc::Channel> channel);

/**
 * Creates a SubscriberStub configured with @p opts and @p channel_id.
 *
 * @p channel_id should be unique among all stubs in the same Connection pool,
 * to ensure they use different underlying connections.
 */
std::shared_ptr<SubscriberStub> CreateDefaultSubscriberStub(Options const& opts,
                                                            int channel_id);

GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
}  // namespace pubsub_internal
}  // namespace cloud
}  // namespace google

#endif  // GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_PUBSUB_INTERNAL_SUBSCRIBER_STUB_FACTORY_H


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:c="http://www.springframework.org/schema/c"
	xmlns:p="http://www.springframework.org/schema/p"
	xmlns:util="http://www.springframework.org/schema/util"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:mybatis="http://mybatis.org/schema/mybatis-spring"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
		http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring.xsd">

	<!-- Registers Database ID provider -->
	<util:properties id="vendorProperties">
		<prop key="SQL Server">sqlserver</prop>
		<prop key="DB2">db2</prop>
		<prop key="Oracle">oracle</prop>
		<prop key="MySQL">mysql</prop>
	</util:properties>

	<bean id="databaseIdProvider" class="org.apache.ibatis.mapping.VendorDatabaseIdProvider"
		p:properties-ref="vendorProperties"/>

	<!-- Registers SQL SessionFactory -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"
		p:typeAliasesPackage="alias"
		p:typeHandlersPackage="handler"
		p:mapperLocations="classpath:conf/mapper/*.xml"
		p:databaseIdProvider-ref="databaseIdProvider"
		p:dataSource-ref="dataSource">
		<property name="configuration">
			<bean class="org.apache.ibatis.session.Configuration"
				p:mapUnderscoreToCamelCase="true"/>
		</property>
	</bean>

	<!-- MyBatis DAO configuration -->
	<mybatis:scan base-package="dao"
		factory-ref="sqlSessionFactory"
		annotation="org.springframework.stereotype.Repository"/>

	<!-- Registers transaction manager -->
	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
		p:dataSource-ref="dataSource" />

	<tx:annotation-driven/>
</beans>


text:
package mysqlctl // import "vitess.io/vitess/go/vt/proto/mysqlctl"

import proto "github.com/golang/protobuf/proto"
import fmt "fmt"
import math "math"

import (
	context "golang.org/x/net/context"
	grpc "google.golang.org/grpc"
)

// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf

// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package

type StartRequest struct {
	MysqldArgs           []string `protobuf:"bytes,1,rep,name=mysqld_args,json=mysqldArgs,proto3" json:"mysqld_args,omitempty"`
	XXX_NoUnkeyedLiteral struct{} `json:"-"`
	XXX_unrecognized     []byte   `json:"-"`
	XXX_sizecache        int32    `json:"-"`
}

func (m *StartRequest) Reset()         { *m = StartRequest{} }
func (m *StartRequest) String() string { return proto.CompactTextString(m) }
func (*StartRequest) ProtoMessage()    {}
func (*StartRequest) Descriptor() ([]byte, []int) {
	return fileDescriptor_mysqlctl_6cf72a3618d6fe7c, []int{0}
}
func (m *StartRequest) XXX_Unmarshal(b []byte) error {
	return xxx_messageInfo_StartRequest.Unmarshal(m, b)
}
func (m *StartRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
	return xxx_messageInfo_StartRequest.Marshal(b, m, deterministic)
}
func (dst *StartRequest) XXX_Merge(src proto.Message) {
	xxx_messageInfo_StartRequest.Merge(dst, src)
}
func (m *StartRequest) XXX_Size() int {
	return xxx_messageInfo_StartRequest.Size(m)
}
func (m *StartRequest) XXX_DiscardUnknown() {
	xxx_messageInfo_StartRequest.DiscardUnknown(m)
}

var xxx_messageInfo_StartRequest proto.InternalMessageInfo

func (m *StartRequest) GetMysqldArgs() []string {
	if m != nil {
		return m.MysqldArgs
	}
	return nil
}

type StartResponse struct {
	XXX_NoUnkeyedLiteral struct{} `json:"-"`
	XXX_unrecognized     []byte   `json:"-"`
	XXX_sizecache        int32    `json:"-"`
}

func (m *StartResponse) Reset()         { *m = StartResponse{} }
func (m *StartResponse) String() string { return proto.CompactTextString(m) }
func (*StartResponse) ProtoMessage()    {}
func (*StartResponse) Descriptor() ([]byte, []int) {
	return fileDescriptor_mysqlctl_6cf72a3618d6fe7c, []int{1}
}
func (m *StartResponse) XXX_Unmarshal(b []byte) error {
	return xxx_messageInfo_StartResponse.Unmarshal(m, b)
}
func (m *StartResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
	return xxx_messageInfo_StartResponse.Marshal(b, m, deterministic)
}
func (dst *StartResponse) XXX_Merge(src proto.Message) {
	xxx_messageInfo_StartResponse.Merge(dst, src)
}
func (m *StartResponse) XXX_Size() int {
	return xxx_messageInfo_StartResponse.Size(m)
}
func (m *StartResponse) XXX_DiscardUnknown() {
	xxx_messageInfo_StartResponse.DiscardUnknown(m)
}

var xxx_messageInfo_StartResponse proto.InternalMessageInfo

type ShutdownRequest struct {
	WaitForMysqld        bool     `protobuf:"varint,1,opt,name=wait_for_mysqld,json=waitForMysqld,proto3" json:"wait_for_mysqld,omitempty"`
	XXX_NoUnkeyedLiteral struct{} `json:"-"`
	XXX_unrecognized     []byte   `json:"-"`
	XXX_sizecache        int32    `json:"-"`
}

func (m *ShutdownRequest) Reset()         { *m = ShutdownRequest{} }
func (m *ShutdownRequest) String() string { return proto.CompactTextString(m) }
func (*ShutdownRequest) ProtoMessage()    {}
func (*ShutdownRequest) Descriptor() ([]byte, []int) {
	return fileDescriptor_mysqlctl_6cf72a3618d6fe7c, []int{2}
}
func (m *ShutdownRequest) XXX_Unmarshal(b []byte) error {
	return xxx_messageInfo_ShutdownRequest.Unmarshal(m, b)
}
func (m *ShutdownRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
	return xxx_messageInfo_ShutdownRequest.Marshal(b, m, deterministic)
}
func (dst *ShutdownRequest) XXX_Merge(src proto.Message) {
	xxx_messageInfo_ShutdownRequest.Merge(dst, src)
}
func (m *ShutdownRequest) XXX_Size() int {
	return xxx_messageInfo_ShutdownRequest.Size(m)
}
func (m *ShutdownRequest) XXX_DiscardUnknown() {
	xxx_messageInfo_ShutdownRequest.DiscardUnknown(m)
}

var xxx_messageInfo_ShutdownRequest proto.InternalMessageInfo

func (m *ShutdownRequest) GetWaitForMysqld() bool {
	if m != nil {
		return m.WaitForMysqld
	}
	return false
}

type ShutdownResponse struct {
	XXX_NoUnkeyedLiteral struct{} `json:"-"`
	XXX_unrecognized     []byte   `json:"-"`
	XXX_sizecache        int32    `json:"-"`
}

func (m *ShutdownResponse) Reset()         { *m = ShutdownResponse{} }
func (m *ShutdownResponse) String() string { return proto.CompactTextString(m) }
func (*ShutdownResponse) ProtoMessage()    {}
func (*ShutdownResponse) Descriptor() ([]byte, []int) {
	return fileDescriptor_mysqlctl_6cf72a3618d6fe7c, []int{3}
}
func (m *ShutdownResponse) XXX_Unmarshal(b []byte) error {
	return xxx_messageInfo_ShutdownResponse.Unmarshal(m, b)
}
func (m *ShutdownResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
	return xxx_messageInfo_ShutdownResponse.Marshal(b, m, deterministic)
}
func (dst *ShutdownResponse) XXX_Merge(src proto.Message) {
	xxx_messageInfo_ShutdownResponse.Merge(dst, src)
}
func (m *ShutdownResponse) XXX_Size() int {
	return xxx_messageInfo_ShutdownResponse.Size(m)
}
func (m *ShutdownResponse) XXX_DiscardUnknown() {
	xxx_messageInfo_ShutdownResponse.DiscardUnknown(m)
}

var xxx_messageInfo_ShutdownResponse proto.InternalMessageInfo

type RunMysqlUpgradeRequest struct {
	XXX_NoUnkeyedLiteral struct{} `json:"-"`
	XXX_unrecognized     []byte   `json:"-"`
	XXX_sizecache        int32    `json:"-"`
}

func (m *RunMysqlUpgradeRequest) Reset()         { *m = RunMysqlUpgradeRequest{} }
func (m *RunMysqlUpgradeRequest) String() string { return proto.CompactTextString(m) }
func (*RunMysqlUpgradeRequest) ProtoMessage()    {}
func (*RunMysqlUpgradeRequest) Descriptor() ([]byte, []int) {
	return fileDescriptor_mysqlctl_6cf72a3618d6fe7c, []int{4}
}
func (m *RunMysqlUpgradeRequest) XXX_Unmarshal(b []byte) error {
	return xxx_messageInfo_RunMysqlUpgradeRequest.Unmarshal(m, b)
}
func (m *RunMysqlUpgradeRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
	return xxx_messageInfo_RunMysqlUpgradeRequest.Marshal(b, m, deterministic)
}
func (dst *RunMysqlUpgradeRequest) XXX_Merge(src proto.Message) {
	xxx_messageInfo_RunMysqlUpgradeRequest.Merge(dst, src)
}
func (m *RunMysqlUpgradeRequest) XXX_Size() int {
	return xxx_messageInfo_RunMysqlUpgradeRequest.Size(m)
}
func (m *RunMysqlUpgradeRequest) XXX_DiscardUnknown() {
	xxx_messageInfo_RunMysqlUpgradeRequest.DiscardUnknown(m)
}

var xxx_messageInfo_RunMysqlUpgradeRequest proto.InternalMessageInfo

type RunMysqlUpgradeResponse struct {
	XXX_NoUnkeyedLiteral struct{} `json:"-"`
	XXX_unrecognized     []byte   `json:"-"`
	XXX_sizecache        int32    `json:"-"`
}

func (m *RunMysqlUpgradeResponse) Reset()         { *m = RunMysqlUpgradeResponse{} }
func (m *RunMysqlUpgradeResponse) String() string { return proto.CompactTextString(m) }
func (*RunMysqlUpgradeResponse) ProtoMessage()    {}
func (*RunMysqlUpgradeResponse) Descriptor() ([]byte, []int) {
	return fileDescriptor_mysqlctl_6cf72a3618d6fe7c, []int{5}
}
func (m *RunMysqlUpgradeResponse) XXX_Unmarshal(b []byte) error {
	return xxx_messageInfo_RunMysqlUpgradeResponse.Unmarshal(m, b)
}
func (m *RunMysqlUpgradeResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
	return xxx_messageInfo_RunMysqlUpgradeResponse.Marshal(b, m, deterministic)
}
func (dst *RunMysqlUpgradeResponse) XXX_Merge(src proto.Message) {
	xxx_messageInfo_RunMysqlUpgradeResponse.Merge(dst, src)
}
func (m *RunMysqlUpgradeResponse) XXX_Size() int {
	return xxx_messageInfo_RunMysqlUpgradeResponse.Size(m)
}
func (m *RunMysqlUpgradeResponse) XXX_DiscardUnknown() {
	xxx_messageInfo_RunMysqlUpgradeResponse.DiscardUnknown(m)
}

var xxx_messageInfo_RunMysqlUpgradeResponse proto.InternalMessageInfo

type ReinitConfigRequest struct {
	XXX_NoUnkeyedLiteral struct{} `json:"-"`
	XXX_unrecognized     []byte   `json:"-"`
	XXX_sizecache        int32    `json:"-"`
}

func (m *ReinitConfigRequest) Reset()         { *m = ReinitConfigRequest{} }
func (m *ReinitConfigRequest) String() string { return proto.CompactTextString(m) }
func (*ReinitConfigRequest) ProtoMessage()    {}
func (*ReinitConfigRequest) Descriptor() ([]byte, []int) {
	return fileDescriptor_mysqlctl_6cf72a3618d6fe7c, []int{6}
}
func (m *ReinitConfigRequest) XXX_Unmarshal(b []byte) error {
	return xxx_messageInfo_ReinitConfigRequest.Unmarshal(m, b)
}
func (m *ReinitConfigRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
	return xxx_messageInfo_ReinitConfigRequest.Marshal(b, m, deterministic)
}
func (dst *ReinitConfigRequest) XXX_Merge(src proto.Message) {
	xxx_messageInfo_ReinitConfigRequest.Merge(dst, src)
}
func (m *ReinitConfigRequest) XXX_Size() int {
	return xxx_messageInfo_ReinitConfigRequest.Size(m)
}
func (m *ReinitConfigRequest) XXX_DiscardUnknown() {
	xxx_messageInfo_ReinitConfigRequest.DiscardUnknown(m)
}

var xxx_messageInfo_ReinitConfigRequest proto.InternalMessageInfo

type ReinitConfigResponse struct {
	XXX_NoUnkeyedLiteral struct{} `json:"-"`
	XXX_unrecognized     []byte   `json:"-"`
	XXX_sizecache        int32    `json:"-"`
}

func (m *ReinitConfigResponse) Reset()         { *m = ReinitConfigResponse{} }
func (m *ReinitConfigResponse) String() string { return proto.CompactTextString(m) }
func (*ReinitConfigResponse) ProtoMessage()    {}
func (*ReinitConfigResponse) Descriptor() ([]byte, []int) {
	return fileDescriptor_mysqlctl_6cf72a3618d6fe7c, []int{7}
}
func (m *ReinitConfigResponse) XXX_Unmarshal(b []byte) error {
	return xxx_messageInfo_ReinitConfigResponse.Unmarshal(m, b)
}
func (m *ReinitConfigResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
	return xxx_messageInfo_ReinitConfigResponse.Marshal(b, m, deterministic)
}
func (dst *ReinitConfigResponse) XXX_Merge(src proto.Message) {
	xxx_messageInfo_ReinitConfigResponse.Merge(dst, src)
}
func (m *ReinitConfigResponse) XXX_Size() int {
	return xxx_messageInfo_ReinitConfigResponse.Size(m)
}
func (m *ReinitConfigResponse) XXX_DiscardUnknown() {
	xxx_messageInfo_ReinitConfigResponse.DiscardUnknown(m)
}

var xxx_messageInfo_ReinitConfigResponse proto.InternalMessageInfo

type RefreshConfigRequest struct {
	XXX_NoUnkeyedLiteral struct{} `json:"-"`
	XXX_unrecognized     []byte   `json:"-"`
	XXX_sizecache        int32    `json:"-"`
}

func (m *RefreshConfigRequest) Reset()         { *m = RefreshConfigRequest{} }
func (m *RefreshConfigRequest) String() string { return proto.CompactTextString(m) }
func (*RefreshConfigRequest) ProtoMessage()    {}
func (*RefreshConfigRequest) Descriptor() ([]byte, []int) {
	return fileDescriptor_mysqlctl_6cf72a3618d6fe7c, []int{8}
}
func (m *RefreshConfigRequest) XXX_Unmarshal(b []byte) error {
	return xxx_messageInfo_RefreshConfigRequest.Unmarshal(m, b)
}
func (m *RefreshConfigRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
	return xxx_messageInfo_RefreshConfigRequest.Marshal(b, m, deterministic)
}
func (dst *RefreshConfigRequest) XXX_Merge(src proto.Message) {
	xxx_messageInfo_RefreshConfigRequest.Merge(dst, src)
}
func (m *RefreshConfigRequest) XXX_Size() int {
	return xxx_messageInfo_RefreshConfigRequest.Size(m)
}
func (m *RefreshConfigRequest) XXX_DiscardUnknown() {
	xxx_messageInfo_RefreshConfigRequest.DiscardUnknown(m)
}

var xxx_messageInfo_RefreshConfigRequest proto.InternalMessageInfo

type RefreshConfigResponse struct {
	XXX_NoUnkeyedLiteral struct{} `json:"-"`
	XXX_unrecognized     []byte   `json:"-"`
	XXX_sizecache        int32    `json:"-"`
}

func (m *RefreshConfigResponse) Reset()         { *m = RefreshConfigResponse{} }
func (m *RefreshConfigResponse) String() string { return proto.CompactTextString(m) }
func (*RefreshConfigResponse) ProtoMessage()    {}
func (*RefreshConfigResponse) Descriptor() ([]byte, []int) {
	return fileDescriptor_mysqlctl_6cf72a3618d6fe7c, []int{9}
}
func (m *RefreshConfigResponse) XXX_Unmarshal(b []byte) error {
	return xxx_messageInfo_RefreshConfigResponse.Unmarshal(m, b)
}
func (m *RefreshConfigResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
	return xxx_messageInfo_RefreshConfigResponse.Marshal(b, m, deterministic)
}
func (dst *RefreshConfigResponse) XXX_Merge(src proto.Message) {
	xxx_messageInfo_RefreshConfigResponse.Merge(dst, src)
}
func (m *RefreshConfigResponse) XXX_Size() int {
	return xxx_messageInfo_RefreshConfigResponse.Size(m)
}
func (m *RefreshConfigResponse) XXX_DiscardUnknown() {
	xxx_messageInfo_RefreshConfigResponse.DiscardUnknown(m)
}

var xxx_messageInfo_RefreshConfigResponse proto.InternalMessageInfo

func init() {
	proto.RegisterType((*StartRequest)(nil), "mysqlctl.StartRequest")
	proto.RegisterType((*StartResponse)(nil), "mysqlctl.StartResponse")
	proto.RegisterType((*ShutdownRequest)(nil), "mysqlctl.ShutdownRequest")
	proto.RegisterType((*ShutdownResponse)(nil), "mysqlctl.ShutdownResponse")
	proto.RegisterType((*RunMysqlUpgradeRequest)(nil), "mysqlctl.RunMysqlUpgradeRequest")
	proto.RegisterType((*RunMysqlUpgradeResponse)(nil), "mysqlctl.RunMysqlUpgradeResponse")
	proto.RegisterType((*ReinitConfigRequest)(nil), "mysqlctl.ReinitConfigRequest")
	proto.RegisterType((*ReinitConfigResponse)(nil), "mysqlctl.ReinitConfigResponse")
	proto.RegisterType((*RefreshConfigRequest)(nil), "mysqlctl.RefreshConfigRequest")
	proto.RegisterType((*RefreshConfigResponse)(nil), "mysqlctl.RefreshConfigResponse")
}

// Reference imports to suppress errors if they are not otherwise used.
var _ context.Context
var _ grpc.ClientConn

// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
const _ = grpc.SupportPackageIsVersion4

// MysqlCtlClient is the client API for MysqlCtl service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.
type MysqlCtlClient interface {
	Start(ctx context.Context, in *StartRequest, opts ...grpc.CallOption) (*StartResponse, error)
	Shutdown(ctx context.Context, in *ShutdownRequest, opts ...grpc.CallOption) (*ShutdownResponse, error)
	RunMysqlUpgrade(ctx context.Context, in *RunMysqlUpgradeRequest, opts ...grpc.CallOption) (*RunMysqlUpgradeResponse, error)
	ReinitConfig(ctx context.Context, in *ReinitConfigRequest, opts ...grpc.CallOption) (*ReinitConfigResponse, error)
	RefreshConfig(ctx context.Context, in *RefreshConfigRequest, opts ...grpc.CallOption) (*RefreshConfigResponse, error)
}

type mysqlCtlClient struct {
	cc *grpc.ClientConn
}

func NewMysqlCtlClient(cc *grpc.ClientConn) MysqlCtlClient {
	return &mysqlCtlClient{cc}
}

func (c *mysqlCtlClient) Start(ctx context.Context, in *StartRequest, opts ...grpc.CallOption) (*StartResponse, error) {
	out := new(StartResponse)
	err := c.cc.Invoke(ctx, "/mysqlctl.MysqlCtl/Start", in, out, opts...)
	if err != nil {
		return nil, err
	}
	return out, nil
}

func (c *mysqlCtlClient) Shutdown(ctx context.Context, in *ShutdownRequest, opts ...grpc.CallOption) (*ShutdownResponse, error) {
	out := new(ShutdownResponse)
	err := c.cc.Invoke(ctx, "/mysqlctl.MysqlCtl/Shutdown", in, out, opts...)
	if err != nil {
		return nil, err
	}
	return out, nil
}

func (c *mysqlCtlClient) RunMysqlUpgrade(ctx context.Context, in *RunMysqlUpgradeRequest, opts ...grpc.CallOption) (*RunMysqlUpgradeResponse, error) {
	out := new(RunMysqlUpgradeResponse)
	err := c.cc.Invoke(ctx, "/mysqlctl.MysqlCtl/RunMysqlUpgrade", in, out, opts...)
	if err != nil {
		return nil, err
	}
	return out, nil
}

func (c *mysqlCtlClient) ReinitConfig(ctx context.Context, in *ReinitConfigRequest, opts ...grpc.CallOption) (*ReinitConfigResponse, error) {
	out := new(ReinitConfigResponse)
	err := c.cc.Invoke(ctx, "/mysqlctl.MysqlCtl/ReinitConfig", in, out, opts...)
	if err != nil {
		return nil, err
	}
	return out, nil
}

func (c *mysqlCtlClient) RefreshConfig(ctx context.Context, in *RefreshConfigRequest, opts ...grpc.CallOption) (*RefreshConfigResponse, error) {
	out := new(RefreshConfigResponse)
	err := c.cc.Invoke(ctx, "/mysqlctl.MysqlCtl/RefreshConfig", in, out, opts...)
	if err != nil {
		return nil, err
	}
	return out, nil
}

// MysqlCtlServer is the server API for MysqlCtl service.
type MysqlCtlServer interface {
	Start(context.Context, *StartRequest) (*StartResponse, error)
	Shutdown(context.Context, *ShutdownRequest) (*ShutdownResponse, error)
	RunMysqlUpgrade(context.Context, *RunMysqlUpgradeRequest) (*RunMysqlUpgradeResponse, error)
	ReinitConfig(context.Context, *ReinitConfigRequest) (*ReinitConfigResponse, error)
	RefreshConfig(context.Context, *RefreshConfigRequest) (*RefreshConfigResponse, error)
}

func RegisterMysqlCtlServer(s *grpc.Server, srv MysqlCtlServer) {
	s.RegisterService(&_MysqlCtl_serviceDesc, srv)
}

func _MysqlCtl_Start_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
	in := new(StartRequest)
	if err := dec(in); err != nil {
		return nil, err
	}
	if interceptor == nil {
		return srv.(MysqlCtlServer).Start(ctx, in)
	}
	info := &grpc.UnaryServerInfo{
		Server:     srv,
		FullMethod: "/mysqlctl.MysqlCtl/Start",
	}
	handler := func(ctx context.Context, req interface{}) (interface{}, error) {
		return srv.(MysqlCtlServer).Start(ctx, req.(*StartRequest))
	}
	return interceptor(ctx, in, info, handler)
}

func _MysqlCtl_Shutdown_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
	in := new(ShutdownRequest)
	if err := dec(in); err != nil {
		return nil, err
	}
	if interceptor == nil {
		return srv.(MysqlCtlServer).Shutdown(ctx, in)
	}
	info := &grpc.UnaryServerInfo{
		Server:     srv,
		FullMethod: "/mysqlctl.MysqlCtl/Shutdown",
	}
	handler := func(ctx context.Context, req interface{}) (interface{}, error) {
		return srv.(MysqlCtlServer).Shutdown(ctx, req.(*ShutdownRequest))
	}
	return interceptor(ctx, in, info, handler)
}

func _MysqlCtl_RunMysqlUpgrade_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
	in := new(RunMysqlUpgradeRequest)
	if err := dec(in); err != nil {
		return nil, err
	}
	if interceptor == nil {
		return srv.(MysqlCtlServer).RunMysqlUpgrade(ctx, in)
	}
	info := &grpc.UnaryServerInfo{
		Server:     srv,
		FullMethod: "/mysqlctl.MysqlCtl/RunMysqlUpgrade",
	}
	handler := func(ctx context.Context, req interface{}) (interface{}, error) {
		return srv.(MysqlCtlServer).RunMysqlUpgrade(ctx, req.(*RunMysqlUpgradeRequest))
	}
	return interceptor(ctx, in, info, handler)
}

func _MysqlCtl_ReinitConfig_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
	in := new(ReinitConfigRequest)
	if err := dec(in); err != nil {
		return nil, err
	}
	if interceptor == nil {
		return srv.(MysqlCtlServer).ReinitConfig(ctx, in)
	}
	info := &grpc.UnaryServerInfo{
		Server:     srv,
		FullMethod: "/mysqlctl.MysqlCtl/ReinitConfig",
	}
	handler := func(ctx context.Context, req interface{}) (interface{}, error) {
		return srv.(MysqlCtlServer).ReinitConfig(ctx, req.(*ReinitConfigRequest))
	}
	return interceptor(ctx, in, info, handler)
}

func _MysqlCtl_RefreshConfig_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
	in := new(RefreshConfigRequest)
	if err := dec(in); err != nil {
		return nil, err
	}
	if interceptor == nil {
		return srv.(MysqlCtlServer).RefreshConfig(ctx, in)
	}
	info := &grpc.UnaryServerInfo{
		Server:     srv,
		FullMethod: "/mysqlctl.MysqlCtl/RefreshConfig",
	}
	handler := func(ctx context.Context, req interface{}) (interface{}, error) {
		return srv.(MysqlCtlServer).RefreshConfig(ctx, req.(*RefreshConfigRequest))
	}
	return interceptor(ctx, in, info, handler)
}

var _MysqlCtl_serviceDesc = grpc.ServiceDesc{
	ServiceName: "mysqlctl.MysqlCtl",
	HandlerType: (*MysqlCtlServer)(nil),
	Methods: []grpc.MethodDesc{
		{
			MethodName: "Start",
			Handler:    _MysqlCtl_Start_Handler,
		},
		{
			MethodName: "Shutdown",
			Handler:    _MysqlCtl_Shutdown_Handler,
		},
		{
			MethodName: "RunMysqlUpgrade",
			Handler:    _MysqlCtl_RunMysqlUpgrade_Handler,
		},
		{
			MethodName: "ReinitConfig",
			Handler:    _MysqlCtl_ReinitConfig_Handler,
		},
		{
			MethodName: "RefreshConfig",
			Handler:    _MysqlCtl_RefreshConfig_Handler,
		},
	},
	Streams:  []grpc.StreamDesc{},
	Metadata: "mysqlctl.proto",
}

func init() { proto.RegisterFile("mysqlctl.proto", fileDescriptor_mysqlctl_6cf72a3618d6fe7c) }

var fileDescriptor_mysqlctl_6cf72a3618d6fe7c = []byte{
	// 339 bytes of a gzipped FileDescriptorProto
	0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x7c, 0x92, 0x4d, 0x4f, 0xfa, 0x30,
	0x1c, 0xc7, 0xff, 0x84, 0xfc, 0xcd, 0xfc, 0x09, 0xce, 0x54, 0x79, 0x6a, 0xa2, 0xe0, 0x12, 0x95,
	0x13, 0x4d, 0xf4, 0xa4, 0x37, 0x25, 0xf1, 0x66, 0x4c, 0x4a, 0x4c, 0x8c, 0x17, 0x32, 0xa5, 0x8c,
	0x26, 0xb8, 0x42, 0x5b, 0x20, 0xbe, 0x05, 0x5f, 0xb5, 0xb1, 0x6b, 0xc7, 0xc6, 0xc0, 0xdb, 0xfa,
	0x7d, 0x6a, 0xf6, 0xd9, 0xe0, 0xf0, 0xf3, 0x4b, 0xcd, 0xa7, 0x1f, 0x7a, 0xda, 0x9b, 0x49, 0xa1,
	0x05, 0xf2, 0xdc, 0x39, 0x20, 0x50, 0x19, 0xe8, 0x50, 0x6a, 0xca, 0xe6, 0x0b, 0xa6, 0x34, 0x6a,
	0xc3, 0x81, 0xf1, 0x46, 0xc3, 0x50, 0x46, 0xaa, 0x59, 0xea, 0x94, 0xbb, 0xfb, 0x14, 0x12, 0xe9,
	0x5e, 0x46, 0x2a, 0xf0, 0xa1, 0x6a, 0x0b, 0x6a, 0x26, 0x62, 0xc5, 0x82, 0x5b, 0xf0, 0x07, 0x93,
	0x85, 0x1e, 0x89, 0x55, 0xec, 0x46, 0x2e, 0xc1, 0x5f, 0x85, 0x5c, 0x0f, 0xc7, 0x42, 0x0e, 0x93,
	0x6a, 0xb3, 0xd4, 0x29, 0x75, 0x3d, 0x5a, 0xfd, 0x95, 0x1f, 0x85, 0x7c, 0x32, 0x62, 0x80, 0xe0,
	0x68, 0x5d, 0xb5, 0x73, 0x4d, 0xa8, 0xd3, 0x45, 0x6c, 0x02, 0x2f, 0xb3, 0x48, 0x86, 0x23, 0x66,
	0x57, 0x83, 0x16, 0x34, 0x0a, 0x8e, 0x2d, 0xd5, 0xe0, 0x98, 0x32, 0x1e, 0x73, 0xdd, 0x17, 0xf1,
	0x98, 0x47, 0xae, 0x51, 0x87, 0x93, 0xbc, 0x6c, 0xe3, 0x46, 0x1f, 0x4b, 0xa6, 0x26, 0xf9, 0x7c,
	0x03, 0x6a, 0x1b, 0x7a, 0x52, 0xb8, 0xfe, 0x2e, 0x83, 0x67, 0x2e, 0xee, 0xeb, 0x29, 0xba, 0x83,
	0xff, 0x86, 0x00, 0xaa, 0xf7, 0x52, 0xac, 0x59, 0x86, 0xb8, 0x51, 0xd0, 0xed, 0xbd, 0xff, 0x50,
	0x1f, 0x3c, 0xf7, 0xc6, 0xa8, 0x95, 0x89, 0xe5, 0x01, 0x62, 0xbc, 0xcd, 0x4a, 0x47, 0x5e, 0xc1,
	0xdf, 0x00, 0x81, 0x3a, 0xeb, 0xc2, 0x76, 0x7a, 0xf8, 0xfc, 0x8f, 0x44, 0xba, 0xfc, 0x0c, 0x95,
	0x2c, 0x30, 0x74, 0x9a, 0x29, 0x15, 0xf9, 0xe2, 0xb3, 0x5d, 0x76, 0x3a, 0x48, 0xa1, 0x9a, 0x23,
	0x8a, 0x72, 0x95, 0xe2, 0x27, 0xc0, 0xed, 0x9d, 0xbe, 0xdb, 0x7c, 0xb8, 0x7a, 0xbb, 0x58, 0x72,
	0xcd, 0x94, 0xea, 0x71, 0x41, 0x92, 0x27, 0x12, 0x09, 0xb2, 0xd4, 0xc4, 0xfc, 0xdc, 0xc4, 0x0d,
	0xbc, 0xef, 0x99, 0xf3, 0xcd, 0x4f, 0x00, 0x00, 0x00, 0xff, 0xff, 0xb8, 0xe2, 0x15, 0x86, 0xfe,
	0x02, 0x00, 0x00,
}


text:
var mongoose = require('mongoose');

module.exports = mongoose.model('User',{
    //_id: mongoose.Schema.Types.ObjectId,
    username: String,
    password: String,
    email: String,
    gender: String,
    address: String
});


text:
<?php echo $title ?>

        <?php echo $body ?>


text:
import _ from "lodash";
import async from "async";
import getPort from "get-port";
import path from "path";
import semver from "semver";

import Command from "../Command";
import FileSystemUtilities from "../FileSystemUtilities";
import NpmUtilities from "../NpmUtilities";
import PackageUtilities from "../PackageUtilities";

export function handler(argv) {
  new BootstrapCommand([...argv.args], argv, argv._cwd).run()
    .then(argv._onFinish, argv._onFinish);
}

export const command = "bootstrap [args..]";

export const describe = "Link local packages together and install remaining package dependencies";

export const builder = {
  "hoist": {
    group: "Command Options:",
    describe: "Install external dependencies matching [glob] to the repo root",
    defaultDescription: "'**'",
    coerce: (arg) => {
      // `--hoist` is equivalent to `--hoist=**`.
      return arg === true ? "**" : arg;
    },
  },
  "nohoist": {
    group: "Command Options:",
    describe: "Don't hoist external dependencies matching [glob] to the repo root",
    type: "string",
  },
  "npm-client": {
    group: "Command Options:",
    describe: "Executable used to install dependencies (npm, yarn, pnpm, ...)",
    type: "string",
    requiresArg: true,
  }
};

export default class BootstrapCommand extends Command {
  get requiresGit() {
    return false;
  }

  initialize(callback) {
    const { registry, npmClient, npmClientArgs, mutex } = this.options;

    this.npmConfig = {
      registry,
      npmClient,
      npmClientArgs,
      mutex
    };

    // lerna bootstrap ... -- <input>
    if (this.input.length) {
      this.npmConfig.npmClientArgs = [...(npmClientArgs || []), ...this.input];
    }

    this.batchedPackages = this.toposort
      ? PackageUtilities.topologicallyBatchPackages(this.filteredPackages)
      : [this.filteredPackages];

    if (npmClient === "yarn" && !mutex) {
      return getPort({ port: 42424, host: '0.0.0.0' }).then((port) => {
        this.npmConfig.mutex = `network:${port}`;
        callback(null, true);
      }).catch(callback);
    }

    callback(null, true);
  }

  execute(callback) {
    this.bootstrapPackages((err) => {
      if (err) {
        callback(err);
      } else {
        this.logger.success("", `Bootstrapped ${this.filteredPackages.length} packages`);
        callback(null, true);
      }
    });
  }

  /**
   * Bootstrap packages
   * @param {Function} callback
   */
  bootstrapPackages(callback) {
    this.logger.info("", `Bootstrapping ${this.filteredPackages.length} packages`);

    const { useWorkspaces } = this.options;

    if (useWorkspaces) {
      this.installRootPackageOnly(callback);
    } else {
      async.series([
        // preinstall bootstrapped packages
        (cb) => this.preinstallPackages(cb),
        // install external dependencies
        (cb) => this.installExternalDependencies(cb),
        // symlink packages and their binaries
        (cb) => this.symlinkPackages(cb),
        // postinstall bootstrapped packages
        (cb) => this.postinstallPackages(cb),
        // prepublish bootstrapped packages
        (cb) => this.prepublishPackages(cb),
        // prepare bootstrapped packages
        (cb) => this.preparePackages(cb)
      ], callback);
    }

  }

  installRootPackageOnly(callback) {
    const tracker = this.logger.newItem("install dependencies");

    NpmUtilities.installInDirOriginalPackageJson(
      this.repository.rootPath,
      this.npmConfig,
      (err) => {
        if (err) return callback(err);
        tracker.info("hoist", "Finished installing in root");
        tracker.completeWork(1);
        callback(err);
      }
    );
  }

  runScriptInPackages(scriptName, callback) {
    if (!this.filteredPackages.length) {
      return callback(null, true);
    }

    const tracker = this.logger.newItem(scriptName);
    tracker.addWork(this.filteredPackages.length);

    PackageUtilities.runParallelBatches(this.batchedPackages, (pkg) => (done) => {
      pkg.runScript(scriptName, (err) => {
        tracker.silly(pkg.name);
        tracker.completeWork(1);
        if (err) {
          err.pkg = pkg;
        }
        done(err);
      });
    }, this.concurrency, (err) => {
      tracker.finish();
      callback(err);
    });
  }

  /**
   * Run the "preinstall" NPM script in all bootstrapped packages
   * @param callback
   */
  preinstallPackages(callback) {
    this.logger.info("lifecycle", "preinstall");
    this.runScriptInPackages("preinstall", callback);
  }

  /**
   * Run the "postinstall" NPM script in all bootstrapped packages
   * @param callback
   */
  postinstallPackages(callback) {
    this.logger.info("lifecycle", "postinstall");
    this.runScriptInPackages("postinstall", callback);
  }

  /**
   * Run the "prepublish" NPM script in all bootstrapped packages
   * @param callback
   */
  prepublishPackages(callback) {
    this.logger.info("lifecycle", "prepublish");
    this.runScriptInPackages("prepublish", callback);
  }

  /**
   * Run the "prepublish" NPM script in all bootstrapped packages
   * @param callback
   */
  preparePackages(callback) {
    this.logger.info("lifecycle", "prepare");
    this.runScriptInPackages("prepare", callback);
  }

  hoistedDirectory(dependency) {
    return path.join(this.repository.rootPath, "node_modules", dependency);
  }

  hoistedPackageJson(dependency) {
    try {
      return require(path.join(this.hoistedDirectory(dependency), "package.json"));
    } catch (e) {
      // Pass.
    }
  }

  /**
   * Determine if a dependency installed at the root satifies the requirements of the passed packages
   * This helps to optimize the bootstrap process and skip dependencies that are already installed
   * @param {String} dependency
   * @param {Array.<String>} packages
   */
  dependencySatisfiesPackages(dependency, packages) {
    const { version } = (this.hoistedPackageJson(dependency) || {});
    return packages.every((pkg) => {
      return semver.satisfies(
        version,
        pkg.allDependencies[dependency]
      );
    });
  }

  /**
   * Return a object of root and leaf dependencies to install
   * @returns {Object}
   */
  getDependenciesToInstall(tracker) {
    // find package by name
    const findPackage = (name, version) => _.find(this.packages, (pkg) => {
      return pkg.name === name && (!version || semver.satisfies(pkg.version, version));
    });

    const hasPackage = (name, version) => Boolean(findPackage(name, version));

    // Configuration for what packages to hoist may be in lerna.json or it may
    // come in as command line options.
    const { hoist, nohoist } = this.options;

    if (hoist) {
      tracker.verbose("hoist", "enabled for %j", hoist);
    }

    // This will contain entries for each hoistable dependency.
    const root = [];

    // This will map packages to lists of unhoistable dependencies
    const leaves = {};

    /**
     * Map of dependencies to install
     * {
     *   <name>: {
     *     versions: {
     *       <version>: <# of dependents>
     *     },
     *     dependents: {
     *       <version>: [<dependent1>, <dependent2>, ...]
     *     }
     *   }
     * }
     *
     * Example:
     *
     * {
     *   react: {
     *     versions: {
     *       "15.x": 3,
     *       "^0.14.0": 1
     *     },
     *     dependents: {
     *       "15.x": ["my-component1", "my-component2", "my-component3"],
     *       "^0.14.0": ["my-component4"],
     *     }
     *   }
     * }
     */
    const depsToInstall = {};

    Object.keys(this.repository.package.allDependencies).forEach((name) => {
      const version = this.repository.package.allDependencies[name];
      depsToInstall[name] = {
        versions   : { [version]: 0 },
        dependents : { [version]: [] },
      };
    });

    // get the map of external dependencies to install
    this.filteredPackages.forEach((pkg) => {

      // for all package dependencies
      Object.keys(pkg.allDependencies)

        // map to package or normalized external dependency
        .map((name) => (
          findPackage(name, pkg.allDependencies[name]) ||
          { name, version: pkg.allDependencies[name] }
        ))

        // match external and version mismatched local packages
        .filter((dep) => !hasPackage(dep.name, dep.version) || !pkg.hasMatchingDependency(dep, true))

        .forEach(({ name, version }) => {
          // Get the object for this package, auto-vivifying.
          const dep = depsToInstall[name] || (depsToInstall[name] = {
            versions   : {},
            dependents : {}
          });

          // Add this version if it's the first time we've seen it.
          if (!dep.versions[version]) {
            dep.versions  [version] = 0;
            dep.dependents[version] = [];
          }

          // Record the dependency on this version.
          dep.versions  [version]++;
          dep.dependents[version].push(pkg.name);
        });
    });

    // determine where each dependency will be installed
    Object.keys(depsToInstall).forEach((name) => {
      const { versions, dependents } = depsToInstall[name];

      let rootVersion;

      if (hoist && PackageUtilities.isHoistedPackage(name, hoist, nohoist)) {
        // Get the most common version.
        const commonVersion = Object.keys(versions)
          .reduce((a, b) => { return versions[a] > versions[b] ? a : b; });

        // Get the version required by the repo root (if any).
        // If the root doesn't have a dependency on this package then we'll
        // install the most common dependency there.
        rootVersion = this.repository.package.allDependencies[name] || commonVersion;

        if (rootVersion !== commonVersion) {
          tracker.warn(
            "EHOIST_ROOT_VERSION",
            `The repository root depends on ${name}@${rootVersion}, ` +
            `which differs from the more common ${name}@${commonVersion}.`
          );
        }

        // Install the best version we can in the repo root.
        // Even if it's already installed there we still need to make sure any
        // binaries are linked to the packages that depend on them.
        root.push({
          name,
          dependents: (dependents[rootVersion] || [])
            .map((dep) => this.packageGraph.get(dep).package),
          dependency: `${name}@${rootVersion}`,
          isSatisfied: this.repository.hasDependencyInstalled(name, rootVersion),
        });
      }

      // Add less common versions to package installs.
      Object.keys(versions).forEach((version) => {
        // Only install deps that can't be hoisted in the leaves.
        if (version === rootVersion) return;

        dependents[version].forEach((pkg) => {
          if (rootVersion) {
            tracker.warn(
              "EHOIST_PKG_VERSION",
              `"${pkg}" package depends on ${name}@${version}, ` +
              `which differs from the hoisted ${name}@${rootVersion}.`
            );
          }

          // only install dependency if it's not already installed
          (leaves[pkg] || (leaves[pkg] = [])).push({
            dependency: `${name}@${version}`,
            isSatisfied: findPackage(pkg).hasDependencyInstalled(name),
          });
        });
      });
    });

    tracker.silly("root dependencies", JSON.stringify(root, null, 2));
    tracker.silly("leaf dependencies", JSON.stringify(leaves, null, 2));

    return { root, leaves };
  }

  /**
   * Install external dependencies for all packages
   * @param {Function} callback
   */
  installExternalDependencies(callback) {
    const tracker = this.logger.newItem("install dependencies");

    const { leaves, root } = this.getDependenciesToInstall(tracker);
    const actions = [];

    // Start root install first, if any, since it's likely to take the longest.
    if (Object.keys(root).length) {

      // If we have anything to install in the root then we'll install
      // _everything_ that needs to go there.  This is important for
      // consistent behavior across npm clients.
      const depsToInstallInRoot = root.some(({ isSatisfied }) => !isSatisfied)
        ? root.map(({ dependency }) => dependency)
        : [];

      actions.push((cb) => {
        if (depsToInstallInRoot.length) {
          tracker.info("hoist", "Installing hoisted dependencies into root");
        }

        NpmUtilities.installInDir(
          this.repository.rootPath,
          depsToInstallInRoot,
          this.npmConfig,
          (err) => {
            if (err) return cb(err);

            // Link binaries into dependent packages so npm scripts will have
            // access to them.
            async.series(root.map(({ name, dependents }) => (cb) => {
              const { bin } = (this.hoistedPackageJson(name) || {});
              if (bin) {
                async.series(dependents.map((pkg) => (cb) => {
                  const src  = this.hoistedDirectory(name);
                  const dest = pkg.nodeModulesLocation;
                  PackageUtilities.createBinaryLink(src, dest, name, bin, cb);
                }), cb);
              } else {
                cb();
              }
            }), (err) => {
              tracker.info("hoist", "Finished installing in root");
              tracker.completeWork(1);
              cb(err);
            });
          }
        );
      });

      // Remove any hoisted dependencies that may have previously been
      // installed in package directories.
      actions.push((cb) => {
        // Compute the list of candidate directories synchronously
        const candidates = root
          .filter((pkg) => pkg.dependents.length)
          .reduce((list, { name, dependents }) => {
            const dirs = dependents.filter(
              (pkg) => pkg.nodeModulesLocation !== this.repository.nodeModulesLocation
            ).map(
              (pkg) => path.join(pkg.nodeModulesLocation, name)
            );

            return list.concat(dirs);
          }, []);

        if (!candidates.length) {
          tracker.verbose("hoist", "nothing to prune");
          tracker.completeWork(1); // the action "work"
          return cb();
        }

        tracker.info("hoist", "Pruning hoisted dependencies");
        tracker.silly("prune", candidates);
        tracker.addWork(candidates.length);

        async.series(candidates.map((dirPath) => (done) => {
          FileSystemUtilities.rimraf(dirPath, (err) => {
            tracker.verbose("prune", dirPath);
            tracker.completeWork(1);
            done(err);
          });
        }), (err) => {
          tracker.info("hoist", "Finished pruning hoisted dependencies");
          tracker.completeWork(1); // the action "work"
          cb(err);
        });
      });
    }

    // Install anything that needs to go into the leaves.
    // Use `npm install --global-style` for leaves when hoisting is enabled
    const npmGlobalStyle = this.options.hoist;
    Object.keys(leaves)
      .map((pkgName) => ({ pkg: this.packageGraph.get(pkgName).package, deps: leaves[pkgName] }))
      .forEach(({ pkg, deps }) => {
        // If we have any unsatisfied deps then we need to install everything.
        // This is important for consistent behavior across npm clients.
        if (deps.some(({ isSatisfied }) => !isSatisfied)) {
          actions.push((cb) => {
            NpmUtilities.installInDir(
              pkg.location,
              deps.map(({ dependency }) => dependency),
              this.npmConfig,
              npmGlobalStyle,
              (err) => {
                tracker.verbose("installed leaf", pkg.name);
                tracker.completeWork(1);
                cb(err);
              }
            );
          });
        }
      });

    if (actions.length) {
      tracker.info("", "Installing external dependencies");
      tracker.verbose("actions", "%d actions, concurrency %d", actions.length, this.concurrency);
      tracker.addWork(actions.length);
    }

    async.parallelLimit(actions, this.concurrency, (err) => {
      tracker.finish();
      callback(err);
    });
  }

  /**
   * Symlink all packages to the packages/node_modules directory
   * Symlink package binaries to dependent packages' node_modules/.bin directory
   * @param {Function} callback
   */
  symlinkPackages(cb) {
    PackageUtilities.symlinkPackages(this.filteredPackages, this.packageGraph, this.logger, cb);
  }
}