text:
package org.deeplearning4j.nn.dataimport.solr.client.solrj.io.stream;

import com.carrotsearch.randomizedtesting.annotations.ThreadLeakFilters;
import com.carrotsearch.randomizedtesting.ThreadFilter;

import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.solr.client.solrj.request.CollectionAdminRequest;
import org.apache.solr.client.solrj.request.UpdateRequest;
import org.apache.solr.cloud.SolrCloudTestCase;
import org.apache.solr.common.SolrInputDocument;
import org.deeplearning4j.nn.api.Model;
import org.deeplearning4j.nn.conf.NeuralNetConfiguration;
import org.deeplearning4j.nn.conf.layers.OutputLayer;
import org.deeplearning4j.nn.multilayer.MultiLayerNetwork;
import org.deeplearning4j.nn.weights.WeightInit;
import org.deeplearning4j.optimize.listeners.ScoreIterationListener;
import org.junit.BeforeClass;
import org.junit.Test;
import org.nd4j.linalg.activations.Activation;
import org.nd4j.linalg.dataset.DataSet;
import org.nd4j.linalg.lossfunctions.LossFunctions.LossFunction;
import org.nd4j.linalg.api.memory.provider.BasicWorkspaceManager;
import org.nd4j.rng.deallocator.NativeRandomDeallocator;

@ThreadLeakFilters(defaultFilters = true, filters = {
  TupleStreamDataSetIteratorTest.PrivateDeallocatorThreadsFilter.class
})
public class TupleStreamDataSetIteratorTest extends SolrCloudTestCase {

  static {
    /*
    This is a hack around the backend-dependent nature of secure random implementations
    though we can set the secure random algorithm in our pom.xml files (via maven surefire and test.solr.allowed.securerandom)
    there isn't a mechanism that is completely platform independent.
    By setting it there (for example, to NativePRNG) that makes it pass on some platforms like Linux but fails on some JVMs on Windows
    For testing purposes, we don't need strict guarantees around RNG, hence we don't want to enforce the RNG algorithm
     */
    String algorithm = new SecureRandom().getAlgorithm();
    System.setProperty("test.solr.allowed.securerandom", algorithm);
  }

  public static class PrivateDeallocatorThreadsFilter implements ThreadFilter {
    /**
     * Reject deallocator threads over whose cleanup this test has no control.
     */
    @Override
    public boolean reject(Thread thread) {
      final ThreadGroup threadGroup = thread.getThreadGroup();
      final String threadGroupName = (threadGroup == null ? null : threadGroup.getName());

      if (threadGroupName != null &&
          threadGroupName.endsWith(TupleStreamDataSetIteratorTest.class.getSimpleName())) {

        final String threadName = thread.getName();
        if (threadName.startsWith(NativeRandomDeallocator.DeallocatorThreadNamePrefix) ||
            threadName.toLowerCase().contains("deallocator") ||
            threadName.equals(BasicWorkspaceManager.WorkspaceDeallocatorThreadName)) {
          return true;
        }
      }

      return false;
    }
  }

  private static int numDocs = 0;

  @BeforeClass
  public static void setupCluster() throws Exception {

    final int numShards = 2;
    final int numReplicas = 2;
    final int maxShardsPerNode = 1;
    final int nodeCount = (numShards*numReplicas + (maxShardsPerNode-1))/maxShardsPerNode;

    // create and configure cluster
    configureCluster(nodeCount)
        .addConfig("conf", configset("mini"))
        .configure();

    // create an empty collection
    CollectionAdminRequest.createCollection("mySolrCollection", "conf", numShards, numReplicas)
        .setMaxShardsPerNode(maxShardsPerNode)
        .process(cluster.getSolrClient());

    // compose an update request
    final UpdateRequest updateRequest = new UpdateRequest();

    final List<Integer> docIds = new ArrayList<Integer>();
    for (int phase = 1; phase <= 2; ++phase) {
      int docIdsIdx = 0;

      if (phase == 2) {
        Collections.shuffle(docIds);
      }

      final int increment = 32;

      for (int b = 0; b <= 256; b += increment) {
        if (256 == b) b--;
        for (int g = 0; g <= 256; g += increment) {
          if (256 == g) g--;
          for (int r = 0; r <= 256; r += increment) {
            if (256 == r) r--;

            if (phase == 1) {
              docIds.add(docIds.size()+1);
              continue;
            }

            final float luminance = (b*0.0722f + g*0.7152f + r*0.2126f)/(255*3.0f); // https://en.wikipedia.org/wiki/Luma_(video)

            final SolrInputDocument doc = sdoc("id", Integer.toString(docIds.get(docIdsIdx++)),
              "channel_b_f", Float.toString(b/255f),
              "channel_g_f", Float.toString(g/255f),
              "channel_r_f", Float.toString(r/255f),
              "luminance_f", Float.toString(luminance));

            updateRequest.add(doc);
            ++numDocs;

          }
        }
      }
    }

    // make the update request
    updateRequest.commit(cluster.getSolrClient(), "mySolrCollection");
  }

  private static class CountingIterationListener extends ScoreIterationListener {

    private int numIterationsDone = 0;

    public CountingIterationListener() {
      super(1);
    }

    public int numIterationsDone() {
      return numIterationsDone;
    }

    @Override
    public void iterationDone(Model model, int iteration, int epoch) {
      super.iterationDone(model, iteration, epoch);
      ++numIterationsDone;
    }

  }

  @Test
  public void iterateTest() throws Exception {
    doIterateTest(true);
    doIterateTest(false);
  }

  private void doIterateTest(boolean withIdKey) throws Exception {

      try (final TupleStreamDataSetIterator
      tsdsi = new TupleStreamDataSetIterator(
        123 /* batch */,
        (withIdKey ? "greeting" : null) /* idKey */,
        new String[] { "pie" },
        new String[] { "answer" },
        "tuple(greeting=\"hello world\",pie=3.14,answer=42)",
        null)) {

      assertTrue(tsdsi.hasNext());
      final DataSet ds = tsdsi.next();

      assertEquals(1, ds.getFeatures().length());
      assertEquals(3.14f, ds.getFeatures().getFloat(0), 0.0f);

      assertEquals(1, ds.getLabels().length());
      assertEquals(42f, ds.getLabels().getFloat(0), 0.0f);

      assertFalse(tsdsi.hasNext());
    }
  }

  @Test
  public void modelFitTest() throws Exception {

    final MultiLayerNetwork model = new MultiLayerNetwork(
      new NeuralNetConfiguration.Builder()
        .list(
          new OutputLayer.Builder(LossFunction.MSE)
            .nIn(3)
            .nOut(1)
            .weightInit(WeightInit.ONES)
            .activation(Activation.IDENTITY)
            .build()
          )

        .build()
      );
    model.init();

    int batch = 1;
    for (int ii=1; ii<=5; ++ii) {
      final CountingIterationListener listener = new CountingIterationListener();
      model.setListeners(listener);
      batch *= 2;

      try (final TupleStreamDataSetIterator tsdsi =
          new TupleStreamDataSetIterator(
            batch,
            "id" /* idKey */,
            new String[] { "channel_b_f", "channel_g_f", "channel_r_f" },
            new String[] { "luminance_f" },
            "search(mySolrCollection," +
            "q=\"id:*\"," +
            "fl=\"id,channel_b_f,channel_g_f,channel_r_f,luminance_f\"," +
            "sort=\"id asc\"," +
            "qt=\"/export\")",
            cluster.getZkClient().getZkServerAddress())) {

        model.fit(tsdsi);
      }

      assertEquals("numIterationsDone="+listener.numIterationsDone()+" numDocs="+numDocs+" batch="+batch,
                   (numDocs+(batch-1))/batch, listener.numIterationsDone());
    }
  }

}


text:
/**
 *
 */
package io.joynr.jeeintegration.messaging;

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

import java.util.concurrent.CompletionStage;
import java.util.concurrent.Future;

import com.google.common.util.concurrent.Futures;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.google.inject.name.Named;

import io.joynr.dispatcher.ServletMessageReceiver;
import io.joynr.jeeintegration.httpbridge.HttpBridgeRegistryClient;
import io.joynr.messaging.MessageArrivedListener;
import io.joynr.messaging.MessagingPropertyKeys;
import io.joynr.messaging.ReceiverStatusListener;
import joynr.ImmutableMessage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static io.joynr.jeeintegration.api.JeeIntegrationPropertyKeys.JEE_ENABLE_HTTP_BRIDGE_CONFIGURATION_KEY;
import static java.lang.String.format;

/**
 * Implementation of a servlet message receiver which is used to register / unregister the channel and also pass on
 * messages and errors to the message listener of the runtime.
 */
@Singleton
public class JeeServletMessageReceiver implements ServletMessageReceiver {

    private static final Logger LOG = LoggerFactory.getLogger(JeeServletMessageReceiver.class);

    private final String channelId;

    private final String hostPath;

    private final String contextRoot;

    private boolean registered = false;

    private MessageArrivedListener messageListener;

    private final HttpBridgeRegistryClient httpBridgeRegistryClient;

    private boolean httpBridgeEnabled;

    @Inject
    public JeeServletMessageReceiver(@Named(MessagingPropertyKeys.CHANNELID) String channelId,
                                     @Named(MessagingPropertyKeys.PROPERTY_SERVLET_CONTEXT_ROOT) String contextRoot,
                                     @Named(MessagingPropertyKeys.PROPERTY_SERVLET_HOST_PATH) String hostPath,
                                     HttpBridgeRegistryClient httpBridgeRegistryClient,
                                     @Named(JEE_ENABLE_HTTP_BRIDGE_CONFIGURATION_KEY) String httpBridgeEnabled) {
        if (LOG.isDebugEnabled()) {
            LOG.debug(format("Initialising with:%n\tchannelId: %s%n\tcontextRoot: %s%n\thostPath: %s%n\thttpBridgeRegistryClient: %s",
                             channelId,
                             contextRoot,
                             hostPath,
                             httpBridgeRegistryClient));
        }
        this.channelId = channelId;
        this.hostPath = hostPath;
        this.contextRoot = contextRoot;
        this.httpBridgeRegistryClient = httpBridgeRegistryClient;
        this.httpBridgeEnabled = Boolean.valueOf(httpBridgeEnabled);
    }

    @Override
    public String getChannelId() {
        return channelId;
    }

    @Override
    public void shutdown(boolean clear) {
        if (registered) {
            LOG.info("Shutting down servlet message receiver.");
            registered = false;
        }
    }

    @Override
    public boolean isReady() {
        return messageListener != null;
    }

    @Override
    public boolean deleteChannel() {
        LOG.info(format("Deleting channel %s", channelId));
        return false;
    }

    @Override
    public boolean isStarted() {
        if (LOG.isDebugEnabled()) {
            LOG.debug(format("isStarted called - returning %s", registered));
        }
        return registered;
    }

    @Override
    public void suspend() {
        LOG.info(format("Suspend called on channel %s, but functionality not supported. Ignoring.", channelId));
    }

    @Override
    public void resume() {
        LOG.info(format("Resume called on channel %s, but functionality not supported. Ignoring.", channelId));
    }

    @Override
    public Future<Void> start(MessageArrivedListener messageArrivedListener,
                              ReceiverStatusListener... receiverStatusListeners) {
        if (messageArrivedListener == null) {
            throw new IllegalStateException();
        }
        LOG.info("Starting JeeServletMessageReceiver with listener {}", messageArrivedListener);
        this.messageListener = messageArrivedListener;
        if (!registered) {
            registerChannelUrl();
        }
        return Futures.immediateFuture(null);
    }

    @Override
    public boolean switchToLongPolling() {
        LOG.info(format("JEE servlet message receiver does not support long polling. Ignoring."));
        return false;
    }

    @Override
    public void receive(ImmutableMessage message) {
        if (message != null) {
            if (LOG.isDebugEnabled()) {
                LOG.debug(format(">>>>>> Message arrived on channel %s:%n\t%s%n", channelId, message));
            }
            messageListener.messageArrived(message);
        } else {
            LOG.warn(format("Received null message on channel %s", channelId));
        }
    }

    @Override
    public void onError(ImmutableMessage message, Throwable error) {
        if (messageListener != null) {
            messageListener.error(message, error);
        } else {
            LOG.warn(format("Channel %s dropped message %s because no message listener available.%nError received: %s",
                            channelId,
                            message,
                            error));
        }
    }

    private synchronized void registerChannelUrl() {
        if (!registered) {
            if (hostPath == null) {
                String message = "The system property hostPath must be set with name:port eg. http://localhost:8080";
                IllegalArgumentException illegalArgumentException = new IllegalArgumentException(message);
                LOG.error(message, illegalArgumentException);
                throw illegalArgumentException;
            }
            if (httpBridgeEnabled) {
                LOG.debug("HTTP Bridge enabled - registering channel with endpoint registry.");
                String endpointUrl = hostPath + contextRoot + "/channels/" + channelId + "/";
                CompletionStage<Void> registrationResult = httpBridgeRegistryClient.register(endpointUrl, channelId);
                registrationResult.thenAccept((v) -> {
                    registered = true;
                }).exceptionally((t) -> {
                    LOG.error("Unable to register channel URL.", t);
                    return null;
                });
            } else {
                LOG.debug("HTTP Bridge disabled.");
                registered = true;
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<link rel="import" href="../../../vaadin-material-styles/color.html">
<link rel="import" href="../../../vaadin-material-styles/font-icons.html">

<dom-module id="material-grid-sorter" theme-for="vaadin-grid-sorter">
  <template>
    <style>
      :host {
        justify-content: flex-start;
        height: 100%;
        align-items: center;
        -webkit-user-select: none;
        -moz-user-select: none;
        user-select: none;
      }

      :host([direction]) {
        color: var(--material-body-text-color);
      }

      [part="indicators"] {
        order: -1;
      }

      [part="indicators"]::before {
        display: inline-block;
        width: 24px;
        font-family: "material-icons";
        font-size: 18px;
        line-height: 18px;
        transition: .1s opacity cubic-bezier(.4, 0, .2, .1), .1s width cubic-bezier(.4, 0, .2, .1);
        opacity: .5;
      }

      :host(:not([direction])) [part="indicators"]::before {
        content: var(--material-icons-arrow-upward);
        width: 0;
        opacity: 0;
      }

      :host([direction]) [part="indicators"]::before {
        opacity: 1;
      }

      :host([direction="asc"]) [part="indicators"]::before {
        content: var(--material-icons-arrow-upward);
      }

      :host([direction="desc"]) [part="indicators"]::before {
        content: var(--material-icons-arrow-downward);
      }

      :host(:hover) [part="indicators"]::before {
        width: 24px;
        opacity: 1;
      }

      [part="order"] {
        right: 4px;
        top: -8px;
        font-size: 10px;
      }
    </style>
  </template>
</dom-module>


text:
<?php

class VP_Control_Field_CodeEditor extends VP_Control_Field
{

	/**
	 * Editor's language mode
	 * (javascript, css, html, php, json, xml, markdown)
	 * @var String
	 */
	protected $_mode;

	/**
	 * Editor's theme
	 * (chaos, chrome, clouds, clouds_midnight, cobalt, crimson_editor, dawn, dreamweaver, eclipse,
	 *  github, mono_industrial, monokai, solarized_dark, solarized_light, textmate, twilight)
	 * @var String
	 */
	protected $_theme;

	public function __construct()
	{
		parent::__construct();
	}

	public static function withArray($arr = array(), $class_name = null)
	{
		if(is_null($class_name))
			$instance = new self();
		else
			$instance = new $class_name;
		$instance->_basic_make($arr);

		$instance->set_editor_mode( isset($arr['mode'])  ? $arr['mode']  : '');
		$instance->set_editor_theme(isset($arr['theme']) ? $arr['theme'] : 'textmate');

		return $instance;
	}

	protected function _setup_data()
	{
		$opt = array(
			'mode'  => $this->get_editor_mode(),
			'theme' => $this->get_editor_theme(),
		);
		$this->add_data('opt', VP_Util_Text::make_opt($opt));
		parent::_setup_data();
	}

	public function render($is_compact = false)
	{
		$this->_setup_data();
		$this->add_data('is_compact', $is_compact);
		return VP_View::instance()->load('control/codeeditor', $this->get_data());
	}

	public function set_value($_value)
	{
		// normalize linebreak to \n for all saved data
		if( is_string($_value) )
		{
			$_value = str_replace(array("\r\n", "\r"), "\n", $_value);
		}
		$this->_value = $_value;
		return $this;
	}

	/**
	 * Get editor's language mode
	 *
	 * @return String Language mode
	 */
	public function get_editor_mode() {
		return $this->_mode;
	}

	/**
	 * Set editor's language mode
	 *
	 * @param String $_mode Language mode
	 */
	public function set_editor_mode($_mode) {
		$this->_mode = $_mode;
		return $this;
	}

	/**
	 * Get editor's theme
	 *
	 * @return String Editor's theme
	 */
	public function get_editor_theme() {
		return $this->_theme;
	}

	/**
	 * Set editor's theme
	 *
	 * @param String $_theme Editor's theme
	 */
	public function set_editor_theme($_theme) {
		$this->_theme = $_theme;
		return $this;
	}

}

/**
 * EOF
 */


text:
const fresh8Config = { instID: '342094' };
// const fresh8Config = { instID: "473256" };

// eslint-disable-next-line no-undef
const fresh8 = new Fresh8(fresh8Config);

const adConfig = { slotID: 'f8-5', appendPoint: 'body', view: 'football' };

fresh8.requestAd(adConfig);

window.fresh8 = fresh8;


text:
@interface WebViewLoadGifVC ()

@end

@implementation WebViewLoadGifVC

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationItem.title = @"webview加载gif";
    self.view.backgroundColor = [UIColor whiteColor];
    self.automaticallyAdjustsScrollViewInsets = NO;

    // 读取gif图片数据
    NSData *data = [NSData dataWithContentsOfFile: [[NSBundle mainBundle] pathForResource:@"testXiDaBian" ofType:@"gif"]];
    UIImage *img = [UIImage imageWithData:data];

    CGFloat width = img.size.width;
    CGFloat height = img.size.height;
    CGFloat x = screenWidth/2.0 - width/2.0;
    CGFloat y = screenHeight/2.0 - height/2.0;

    UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(x, y, width, height)];
    [webView loadData:data MIMEType:@"image/gif" textEncodingName:nil baseURL:nil];
    [self.view addSubview:webView];

}

- (void)dealloc
{
    [Tools NSLogClassDestroy:self];

}

@end


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="AWSSDK.CognitoIdentity.Sample" android:versionCode="1" android:versionName="1.0">
	<uses-sdk />
	<application android:label="AWSSDK.CognitoIdentity.Sample" android:icon="@drawable/Icon"></application>
</manifest>


text:
The code in this repository is not maintained, and serves as an example only. In particular, security patches are not
applied for out-of-date dependencies, and tools like GitHub's dependabot are not running.

### Overview

`richobject` is an experiment to create a spring-data repository for constructing repositories that provide rich objects,
with dependency-injected collaborators that allow them to take part in the full range of object-oriented interactions.

## motivation

Technologies like JPA, JAXB, and friends all make it very easy to turn our objects into something we can send on the
wire, or put in a database, or otherwise represent in a remotely-recreatable-form. This project is an experiment to
see what it looks like if we ask for _objects_ out of our repositories, instead of _piece of data_. The idea being
to reduce the number of layers between our domain logic and our persistence stores - and reduce the friction that gets
in the way of practicing object-oriented programming (rather than passing data between service singletons).

## usage

The tests wire up a functioning `TestDomainObjectRepository`, which is backed by a persistent JPA entity. Take a look
in `RichRepositoryConfiguration` to see how to wire up a `richobject` repository - note that:
* `richobject` assumes your persistence layer is backed by a jpa-repository
* You will need to provide an appropriate `@Scope("prototype")` bean for `rich-object` to be able to provide
instances of your domain class.

# building

Maven is the build-system of choice. Note that some tests are written with scala-test, so maven will grab the
`scala-maven-plugin` for you.


text:
var Alloy = require("alloy"), _ = require("alloy/underscore")._, model, collection;

exports.definition = {
    config: {
        adapter: {
            type: "acs",
            collection_name: "users"
        }
    },
    extendModel: function(Model) {
        _.extend(Model.prototype, {
            login: function(_login, _password, _callback) {
                this.config.Cloud.Users.login({
                    login: _login,
                    password: _password
                }, function(e) {
                    if (e.success) {
                        var user = e.users[0];
                        Ti.App.Properties.setString("sessionId", e.meta.session_id);
                        Ti.App.Properties.setString("user", JSON.stringify(user));
                        _callback && _callback({
                            success: true,
                            model: new model(user)
                        });
                    } else {
                        Ti.API.error(e);
                        _callback && _callback({
                            success: false,
                            model: null,
                            error: e
                        });
                    }
                });
            },
            createAccount: function(_ucerInfo, _callback) {
                var cloud = this.config.Cloud;
                var TAP = Ti.App.Properties;
                _userInfo ? cloud.Users.create(_userInfo, function(e) {
                    if (e.success) {
                        var user = e.users[0];
                        TAP.setString("sessionId", e.meta.session_id);
                        TAP.setString("user", JSON.stringify(user));
                        cloud.sessionId = e.meta.session_id;
                        _callback && callback({
                            success: true,
                            model: new model(user)
                        });
                    } else {
                        Ti.API.error(e);
                        __callback && _callback({
                            success: false,
                            model: null,
                            error: e
                        });
                    }
                }) : _callback && _callback({
                    success: false,
                    model: null
                });
            },
            logout: function(_callback) {
                var cloud = this.config.Cloud;
                var TAP = Ti.App.Properties;
                cloud.Users.logout(function(e) {
                    if (e.success) {
                        {
                            e.users[0];
                        }
                        TAP.removeProperty("sessionId");
                        TAP.removeProperty("user");
                        _callback && _callback({
                            success: true,
                            model: null
                        });
                    } else {
                        Ti.API.error(e);
                        _callback && _callback({
                            success: false,
                            model: null,
                            error: e
                        });
                    }
                });
            },
            authenticated: function() {
                var cloud = this.config.Cloud;
                var TAP = Ti.App.Properties;
                if (TAP.hasProperty("sessionId")) {
                    Ti.API.info("SESSION ID: " + TAP.getString("SessionId"));
                    cloud.sessionId = TAP.getString("SessionId");
                    return true;
                }
                return false;
            },
            showMe: function(_callback) {
                var cloud = this.config.Cloud;
                var TAP = Ti.App.Properties;
                cloud.Users.showMe(function(e) {
                    if (e.success) {
                        var user = e.users[0];
                        TAP.setString("sessionId", e.meta.session_id);
                        TAP.setString("user", JSON.stringify(user));
                        _callback && _callback({
                            success: true,
                            model: new model(user)
                        });
                    } else {
                        Ti.App.error(e);
                        TAP.removeProperty("sessionId");
                        TAP.removeProperty("user");
                        _callback && _callback({
                            success: false,
                            model: null,
                            error: e
                        });
                    }
                });
            },
            updateFacebookLoginStatus: function(_accessToken, _opts) {
                var cloud = this.config.Cloud;
                var TAP = Ti.App.Properties;
                if (false == Alloy.Globals.FB.loggedIn) {
                    _opts.error && _opts.error({
                        success: false,
                        model: null,
                        error: "Not Logged into Facebook"
                    });
                    alert("Please Log Into Facebook first");
                    return;
                }
                cloud.SocialIntegrations.externalAccountLogin({
                    type: "facebook",
                    token: _accessToken
                }, function(e) {
                    if (e.success) {
                        var user = e.users[0];
                        TAP.setString("sessionId", e.meta.session_id);
                        TAP.setString("user", JSON.stringify(user));
                        TAP.setString("loginType", "FACEBOOK");
                        _opts.success && _opts.success({
                            success: true,
                            model: new model(user),
                            error: null
                        });
                    } else {
                        Ti.API.error(e);
                        _opts.error && _opts.error({
                            success: false,
                            model: null,
                            error: e
                        });
                    }
                });
            },
            getFollowers: function(_callback, _followers) {
                var followers = Alloy.createCollection("Friend");
                followers.fetch({
                    data: {
                        per_page: 100,
                        q: " ",
                        user_id: this.id,
                        followers: _followers || "true"
                    },
                    success: function(_collection) {
                        _callback && _callback({
                            success: true,
                            collection: _collection
                        });
                    },
                    error: function(_model, _response) {
                        _callback && _callback({
                            success: false,
                            collection: {},
                            error: _response
                        });
                    }
                });
            },
            getFriends: function(_callback) {
                this.getFollowers(_callback, false);
            },
            followUser: function(_userid, _callback) {
                var friendItem = {
                    user_ids: _userid,
                    approval_required: "false"
                };
                var friendItemModel = Alloy.createModel("Friend");
                friendItemModel.save(friendItem, {
                    success: function() {
                        _callback({
                            success: true
                        });
                    },
                    error: function() {
                        _callback({
                            success: false
                        });
                    }
                });
            },
            unFollowUser: function(_userid, _callback) {
                var friendItemModel = Alloy.createModel("Friend");
                friendItemModel.id = _userid;
                friendItemModel.destroy({
                    data: {
                        user_ids: [ _userid ]
                    },
                    success: function() {
                        _callback({
                            success: true
                        });
                    },
                    error: function() {
                        _callback({
                            success: false
                        });
                    }
                });
            }
        });
        return Model;
    },
    extendCollection: function(Collection) {
        _.extend(Collection.prototype, {});
        return Collection;
    }
};

model = Alloy.M("user", exports.definition, []);

collection = Alloy.C("user", exports.definition, model);

exports.Model = model;

exports.Collection = collection;


text:
class AddPointOfContactToClub < ActiveRecord::Migration[5.0]
  def change
    add_reference :clubs, :point_of_contact, index: true
    add_foreign_key :clubs, :leaders, column: :point_of_contact_id
  end
end


text:
package pmm.pbm.service.cms;

import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.stream.Collectors;

import javax.annotation.PreDestroy;
import javax.servlet.ServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.WebApplicationContext;

import lombok.Getter;
import lombok.NonNull;
import lombok.val;
import pmm.pbm.data.base.support.Paged;
import pmm.pbm.util.WebUtils;
import pmm.pbm.util.cms.HiddenField;
import pmm.pbm.util.cms.QueryField;
import pw.phylame.ycl.function.Prediction;
import pw.phylame.ycl.util.Reflections;
import pw.phylame.ycl.util.StringUtils;
import pw.phylame.ycl.value.Pair;

@Service
public class CMSService {
    private static final Logger logger = LoggerFactory.getLogger(CMSService.class);

    @Autowired
    private WebApplicationContext context;

    private final Map<String, ItemWorker> workers = new HashMap<>();

    @PreDestroy
    public void cleanup() {
        workers.clear();
    }

    @Transactional
    public ItemWorker getWorker(String tag) {
        ItemWorker worker = workers.get(tag);
        if (worker != null && worker.found) {
            return worker;
        }
        workers.put(tag, worker = new ItemWorker());

        worker.tag = tag;

        try {
            worker.service = context.getBean("cms" + StringUtils.capitalized(tag) + "Service");
        } catch (BeansException e) {
            logger.debug("not found cms service instance in Spring", e);
            return null;
        }

        worker.found = true;
        return worker;
    }

    @Getter(lazy = true)
    private final Properties orders = loadOrderProperties();

    private Properties loadOrderProperties() {
        val prop = new Properties();
        try {
            prop.load(context.getResource("classpath:config/order.properties").getInputStream());
        } catch (IOException e) {
            logger.error("cannot load order settings", e);
        }
        return prop;
    }

    private Comparator<Field> getFieldComparator(String tag) {
        return (o1, o2) -> {
            val orders = getOrders();
            val key1 = orders.getProperty(tag + '.' + o1.getName());
            val key2 = orders.getProperty(tag + '.' + o2.getName());
            return key1 == null || key2 == null ? 0 : key1.compareTo(key2);
        };
    }

    @Getter
    private class Unit {

        private String name;

        private String type;
    }

    public class ItemWorker {
        // all of worker found
        private boolean found = false;

        @Getter
        private String tag;

        private Object service;

        private Class<?> voType;

        private Class<?> idType;

        private Class<?> dtoType;

        @Getter(lazy = true)
        private final List<Unit> queryUnits = findQueryUnits();

        @Getter(lazy = true)
        private final List<Unit> itemUnits = findItemUnits();

        @Getter(lazy = true)
        private final Method getMethod = findGetMethod();

        @Getter(lazy = true)
        private final Method listMethod = findListMethod();

        private List<Unit> findQueryUnits() {
            if (dtoType == null) {
                logger.error("dtoType is null");
                return null;
            }
            return getUnits(dtoType,
                    i -> !Modifier.isStatic(i.getModifiers()) && i.isAnnotationPresent(QueryField.class));
        }

        private List<Unit> findItemUnits() {
            if (voType == null) {
                getGetMethod();
            }
            if (voType == null) {
                logger.error("voType is null");
                return null;
            }
            return getUnits(voType,
                    i -> !Modifier.isStatic(i.getModifiers()) && !i.isAnnotationPresent(HiddenField.class));
        }

        private List<Unit> getUnits(Class<?> clazz, Prediction<Field> prediction) {
            return Reflections.getFields(clazz, prediction)
                    .stream()
                    .sorted(getFieldComparator(tag))
                    .map(field -> {
                        val unit = new Unit();
                        unit.name = field.getName();
                        unit.type = field.getType().getSimpleName();
                        return unit;
                    })
                    .collect(Collectors.toList());
        }

        private Method findGetMethod() {
            val name = "get" + StringUtils.capitalized(tag) + "ById";
            val value = Arrays.stream(service.getClass().getMethods())
                    .filter(m -> m.getParameterCount() == 1
                            && m.getReturnType() != void.class
                            && m.getName().equals(name))
                    .findFirst();
            if (!value.isPresent()) {
                logger.error("not found get method({}) of cms service({})", name, service);
                return null;
            }
            val method = value.get();
            idType = method.getParameterTypes()[0];
            voType = method.getReturnType();
            return method;
        }

        private Method findListMethod() {
            val name = "get" + StringUtils.capitalized(tag) + "Paged";
            val value = Arrays.stream(service.getClass().getMethods())
                    .filter(m -> m.getParameterCount() == 1
                            && Paged.class.isAssignableFrom(m.getReturnType())
                            && m.getName().equals(name))
                    .findFirst();
            if (!value.isPresent()) {
                logger.error("not found list method({}) of cms service: {}", name, service);
                return null;
            }
            val method = value.get();
            dtoType = method.getParameterTypes()[0];
            return method;
        }

        public Pair<Object, Object> getPaged(ServletRequest request) {
            if (service == null) {
                throw new IllegalStateException("CMS service is null");
            }
            val method = getListMethod();
            if (method == null) {
                return null;
            }
            val dto = WebUtils.getObjectParameter(dtoType, request);
            Object results = null;
            try {
                results = method.invoke(service, dto);
                if (results == null) {
                    logger.error("list method({}) of cms service({}) returned null", method.getName(), service);
                } else if (voType == null) {
                    val paged = ((Paged<?>) results);
                    if (paged.getTotal() > 0) {
                        voType = paged.get(0).getClass();
                    }
                }
            } catch (IllegalAccessException | InvocationTargetException e) {
                logger.error("cannot invoke list method({}) of cms service({})", method.getName(), service);
                logger.debug("traceback: ", e);
            }
            return new Pair<>(dto, results);
        }

        public Object getById(@NonNull String id) {
            if (service == null) {
                throw new IllegalStateException("CMS service is null");
            }
            val method = getGetMethod();
            if (method == null) {
                return null;
            }
            val _id = WebUtils.getValueParameter(idType, id);
            Object result = null;
            try {
                result = method.invoke(service, _id);
                if (result == null) {
                    logger.error("get method({}) of cms service({}) returned null", method.getName(), service);
                }
            } catch (IllegalAccessException | InvocationTargetException e) {
                logger.error("cannot invoke get method({}) of cms service({})", e, method.getName(), service);
                logger.debug("traceback: ", e);
            }
            return result;
        }
    }
}


text:
Template.userCreation.onCreated(function(){
  this.csv = new ReactiveVar("");
  this.ready = new ReactiveVar(false);
  this.error = new ReactiveVar(false);
  this.users = new ReactiveVar([]);
});

Template.userCreation.helpers({
  error: function(){
    return Template.instance().error.get();
  },
  ready: function(){
    return Template.instance().ready.get();
  },
  formattedUsers: function(){
    return Template.instance().users.get();
  }
});

Template.userCreation.events({
  "click #checkFormat": function(e, t){
    // Reset the error
    t.error.set(false);

    // Grab the csv text
    var csv = $('#usersCsv').val();

    try {
      t.users.set(formatCsv(csv, t));
      t.ready.set(true);
    } catch(err){
      t.error.set(err);
      t.ready.set(false);
    }
  },
  "click #createUsers": function(e, t){
    // Create the users one by one
    t.users.get().forEach(function(user, idx){
      Meteor.call("createAccount",
          user.username,
          user.password,
          user.profile,
          function(error){
            if (error){
              user.failed = true;
            } else {
              user.success = true;
            }
            var u = t.users.get();
            u[idx] = user;
            t.users.set(u);
          });
    });
  }
});

function formatCsv(csv, t){
  var rows = csv.split('\n');

  if (csv.length == 0){
    throw "There's nothing here.";
  }

  var users = {};

  return rows.map(function(row, i){
    var columns = row.split(',');

    if (columns.length < 3){
      throw "Row " + i + " has " + columns.length + " values, expected 3";
    }

    if (columns.length > 3){
      throw "Row " + i + " has " + columns.length + " values, expected 3";
    }

    var username = columns[0].trim(),
        password = columns[1].trim(),
        name     = columns[2].trim();

    // Ensure the username is unique
    if (users[username]) {
      throw "Duplicate username: " + username;
    }

    // Ensure the password is at least 6 characters
    if (password.length < 6){
      throw "Row " + i + " password too short, must be 6 characters or more";
    }

    // Keep track of this username
    users[username] = true;

    return {
      username: username,
      password: password,
      profile: {
        name: name
      }
    }
  })

}


text:
/*
 * This file contains Original Code and/or Modifications of Original Code
 * as defined in and that are subject to the Apache License
 * Version 2.0 (the 'License'). You may not use this file except in
 * compliance with the License. Please obtain a copy of the License at
 * http://opensource.org/licenses/Apache-2.0/ and read it before using this
 * file.
 *
 * The Original Code and all software distributed under the License are
 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
 * Please see the License for the specific language governing rights and
 * limitations under the License.
 */

#import <Cordova/CDVPlugin.h>

@interface APPBadge : CDVPlugin

// Load the badge config
- (void) load:(CDVInvokedUrlCommand *)command;
// Save the badge config
- (void) save:(CDVInvokedUrlCommand *)command;
// Clear the badge number
- (void) clear:(CDVInvokedUrlCommand *)command;
// Set the badge number
- (void) set:(CDVInvokedUrlCommand *)command;
// Get the badge number
- (void) get:(CDVInvokedUrlCommand *)command;
// Check permission to show badges
- (void) check:(CDVInvokedUrlCommand *)command;
// Request permission to show badges
- (void) request:(CDVInvokedUrlCommand *)command;

@end


text:
import {
  global,
  phxWindow,
  CHANNEL_EVENTS,
  DEFAULT_TIMEOUT,
  DEFAULT_VSN,
  SOCKET_STATES,
  TRANSPORTS,
  WS_CLOSE_NORMAL
} from "./constants"

import {
  closure
} from "./utils"

import Ajax from "./ajax"
import Channel from "./channel"
import LongPoll from "./longpoll"
import Serializer from "./serializer"
import Timer from "./timer"

/** Initializes the Socket *
 *
 * For IE8 support use an ES5-shim (https://github.com/es-shims/es5-shim)
 *
 * @param {string} endPoint - The string WebSocket endpoint, ie, `"ws://example.com/socket"`,
 *                                               `"wss://example.com"`
 *                                               `"/socket"` (inherited host & protocol)
 * @param {Object} [opts] - Optional configuration
 * @param {Function} [opts.transport] - The Websocket Transport, for example WebSocket or Phoenix.LongPoll.
 *
 * Defaults to WebSocket with automatic LongPoll fallback.
 * @param {Function} [opts.encode] - The function to encode outgoing messages.
 *
 * Defaults to JSON encoder.
 *
 * @param {Function} [opts.decode] - The function to decode incoming messages.
 *
 * Defaults to JSON:
 *
 * ```javascript
 * (payload, callback) => callback(JSON.parse(payload))
 * ```
 *
 * @param {number} [opts.timeout] - The default timeout in milliseconds to trigger push timeouts.
 *
 * Defaults `DEFAULT_TIMEOUT`
 * @param {number} [opts.heartbeatIntervalMs] - The millisec interval to send a heartbeat message
 * @param {number} [opts.reconnectAfterMs] - The optional function that returns the millisec
 * socket reconnect interval.
 *
 * Defaults to stepped backoff of:
 *
 * ```javascript
 * function(tries){
 *   return [10, 50, 100, 150, 200, 250, 500, 1000, 2000][tries - 1] || 5000
 * }
 * ````
 *
 * @param {number} [opts.rejoinAfterMs] - The optional function that returns the millisec
 * rejoin interval for individual channels.
 *
 * ```javascript
 * function(tries){
 *   return [1000, 2000, 5000][tries - 1] || 10000
 * }
 * ````
 *
 * @param {Function} [opts.logger] - The optional function for specialized logging, ie:
 *
 * ```javascript
 * function(kind, msg, data) {
 *   console.log(`${kind}: ${msg}`, data)
 * }
 * ```
 *
 * @param {number} [opts.longpollerTimeout] - The maximum timeout of a long poll AJAX request.
 *
 * Defaults to 20s (double the server long poll timer).
 *
 * @param {(Object|function)} [opts.params] - The optional params to pass when connecting
 * @param {string} [opts.binaryType] - The binary type to use for binary WebSocket frames.
 *
 * Defaults to "arraybuffer"
 *
 * @param {vsn} [opts.vsn] - The serializer's protocol version to send on connect.
 *
 * Defaults to DEFAULT_VSN.
*/
export default class Socket {
  constructor(endPoint, opts = {}){
    this.stateChangeCallbacks = {open: [], close: [], error: [], message: []}
    this.channels = []
    this.sendBuffer = []
    this.ref = 0
    this.timeout = opts.timeout || DEFAULT_TIMEOUT
    this.transport = opts.transport || global.WebSocket || LongPoll
    this.establishedConnections = 0
    this.defaultEncoder = Serializer.encode.bind(Serializer)
    this.defaultDecoder = Serializer.decode.bind(Serializer)
    this.closeWasClean = false
    this.binaryType = opts.binaryType || "arraybuffer"
    this.connectClock = 1
    if(this.transport !== LongPoll){
      this.encode = opts.encode || this.defaultEncoder
      this.decode = opts.decode || this.defaultDecoder
    } else {
      this.encode = this.defaultEncoder
      this.decode = this.defaultDecoder
    }
    let awaitingConnectionOnPageShow = null
    if(phxWindow && phxWindow.addEventListener){
      phxWindow.addEventListener("pagehide", _e => {
        if(this.conn){
          this.disconnect()
          awaitingConnectionOnPageShow = this.connectClock
        }
      })
      phxWindow.addEventListener("pageshow", _e => {
        if(awaitingConnectionOnPageShow === this.connectClock){
          awaitingConnectionOnPageShow = null
          this.connect()
        }
      })
    }
    this.heartbeatIntervalMs = opts.heartbeatIntervalMs || 30000
    this.rejoinAfterMs = (tries) => {
      if(opts.rejoinAfterMs){
        return opts.rejoinAfterMs(tries)
      } else {
        return [1000, 2000, 5000][tries - 1] || 10000
      }
    }
    this.reconnectAfterMs = (tries) => {
      if(opts.reconnectAfterMs){
        return opts.reconnectAfterMs(tries)
      } else {
        return [10, 50, 100, 150, 200, 250, 500, 1000, 2000][tries - 1] || 5000
      }
    }
    this.logger = opts.logger || null
    this.longpollerTimeout = opts.longpollerTimeout || 20000
    this.params = closure(opts.params || {})
    this.endPoint = `${endPoint}/${TRANSPORTS.websocket}`
    this.vsn = opts.vsn || DEFAULT_VSN
    this.heartbeatTimeoutTimer = null
    this.heartbeatTimer = null
    this.pendingHeartbeatRef = null
    this.reconnectTimer = new Timer(() => {
      this.teardown(() => this.connect())
    }, this.reconnectAfterMs)
  }

  /**
   * Returns the LongPoll transport reference
   */
  getLongPollTransport(){ return LongPoll }

  /**
   * Disconnects and replaces the active transport
   *
   * @param {Function} newTransport - The new transport class to instantiate
   *
   */
  replaceTransport(newTransport){
    this.connectClock++
    this.closeWasClean = true
    this.reconnectTimer.reset()
    this.sendBuffer = []
    if(this.conn){
      this.conn.close()
      this.conn = null
    }
    this.transport = newTransport
  }

  /**
   * Returns the socket protocol
   *
   * @returns {string}
   */
  protocol(){ return location.protocol.match(/^https/) ? "wss" : "ws" }

  /**
   * The fully qualified socket url
   *
   * @returns {string}
   */
  endPointURL(){
    let uri = Ajax.appendParams(
      Ajax.appendParams(this.endPoint, this.params()), {vsn: this.vsn})
    if(uri.charAt(0) !== "/"){ return uri }
    if(uri.charAt(1) === "/"){ return `${this.protocol()}:${uri}` }

    return `${this.protocol()}://${location.host}${uri}`
  }

  /**
   * Disconnects the socket
   *
   * See https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent#Status_codes for valid status codes.
   *
   * @param {Function} callback - Optional callback which is called after socket is disconnected.
   * @param {integer} code - A status code for disconnection (Optional).
   * @param {string} reason - A textual description of the reason to disconnect. (Optional)
   */
  disconnect(callback, code, reason){
    this.connectClock++
    this.closeWasClean = true
    this.reconnectTimer.reset()
    this.teardown(callback, code, reason)
  }

  /**
   *
   * @param {Object} params - The params to send when connecting, for example `{user_id: userToken}`
   *
   * Passing params to connect is deprecated; pass them in the Socket constructor instead:
   * `new Socket("/socket", {params: {user_id: userToken}})`.
   */
  connect(params){
    if(params){
      console && console.log("passing params to connect is deprecated. Instead pass :params to the Socket constructor")
      this.params = closure(params)
    }
    if(this.conn){ return }

    this.connectClock++
    this.closeWasClean = false
    this.conn = new this.transport(this.endPointURL())
    this.conn.binaryType = this.binaryType
    this.conn.timeout = this.longpollerTimeout
    this.conn.onopen = () => this.onConnOpen()
    this.conn.onerror = error => this.onConnError(error)
    this.conn.onmessage = event => this.onConnMessage(event)
    this.conn.onclose = event => this.onConnClose(event)
  }

  /**
   * Logs the message. Override `this.logger` for specialized logging. noops by default
   * @param {string} kind
   * @param {string} msg
   * @param {Object} data
   */
  log(kind, msg, data){ this.logger(kind, msg, data) }

  /**
   * Returns true if a logger has been set on this socket.
   */
  hasLogger(){ return this.logger !== null }

  /**
   * Registers callbacks for connection open events
   *
   * @example socket.onOpen(function(){ console.info("the socket was opened") })
   *
   * @param {Function} callback
   */
  onOpen(callback){
    let ref = this.makeRef()
    this.stateChangeCallbacks.open.push([ref, callback])
    return ref
  }

  /**
   * Registers callbacks for connection close events
   * @param {Function} callback
   */
  onClose(callback){
    let ref = this.makeRef()
    this.stateChangeCallbacks.close.push([ref, callback])
    return ref
  }

  /**
   * Registers callbacks for connection error events
   *
   * @example socket.onError(function(error){ alert("An error occurred") })
   *
   * @param {Function} callback
   */
  onError(callback){
    let ref = this.makeRef()
    this.stateChangeCallbacks.error.push([ref, callback])
    return ref
  }

  /**
   * Registers callbacks for connection message events
   * @param {Function} callback
   */
  onMessage(callback){
    let ref = this.makeRef()
    this.stateChangeCallbacks.message.push([ref, callback])
    return ref
  }

  /**
   * Pings the server and invokes the callback with the RTT in milliseconds
   * @param {Function} callback
   *
   * Returns true if the ping was pushed or false if unable to be pushed.
   */
  ping(callback){
    if(!this.isConnected()){ return false }
    let ref = this.makeRef()
    let startTime = Date.now()
    this.push({topic: "phoenix", event: "heartbeat", payload: {}, ref: ref})
    let onMsgRef = this.onMessage(msg => {
      if(msg.ref === ref){
        this.off([onMsgRef])
        callback(Date.now() - startTime)
      }
    })
    return true
  }

  /**
   * @private
   */

  clearHeartbeats(){
    clearTimeout(this.heartbeatTimer)
    clearTimeout(this.heartbeatTimeoutTimer)
  }

  onConnOpen(){
    if(this.hasLogger()) this.log("transport", `connected to ${this.endPointURL()}`)
    this.closeWasClean = false
    this.establishedConnections++
    this.flushSendBuffer()
    this.reconnectTimer.reset()
    this.resetHeartbeat()
    this.stateChangeCallbacks.open.forEach(([, callback]) => callback())
  }

  /**
   * @private
   */

  heartbeatTimeout(){
    if(this.pendingHeartbeatRef){
      this.pendingHeartbeatRef = null
      if(this.hasLogger()){ this.log("transport", "heartbeat timeout. Attempting to re-establish connection") }
      this.triggerChanError()
      this.closeWasClean = false
      this.teardown(() => this.reconnectTimer.scheduleTimeout(), WS_CLOSE_NORMAL, "heartbeat timeout")
    }
  }

  resetHeartbeat(){
    if(this.conn && this.conn.skipHeartbeat){ return }
    this.pendingHeartbeatRef = null
    this.clearHeartbeats()
    this.heartbeatTimer = setTimeout(() => this.sendHeartbeat(), this.heartbeatIntervalMs)
  }

  teardown(callback, code, reason){
    if(!this.conn){
      return callback && callback()
    }

    this.waitForBufferDone(() => {
      if(this.conn){
        if(code){ this.conn.close(code, reason || "") } else { this.conn.close() }
      }

      this.waitForSocketClosed(() => {
        if(this.conn){
          this.conn.onopen = function (){ } // noop
          this.conn.onerror = function (){ } // noop
          this.conn.onmessage = function (){ } // noop
          this.conn.onclose = function (){ } // noop
          this.conn = null
        }

        callback && callback()
      })
    })
  }

  waitForBufferDone(callback, tries = 1){
    if(tries === 5 || !this.conn || !this.conn.bufferedAmount){
      callback()
      return
    }

    setTimeout(() => {
      this.waitForBufferDone(callback, tries + 1)
    }, 150 * tries)
  }

  waitForSocketClosed(callback, tries = 1){
    if(tries === 5 || !this.conn || this.conn.readyState === SOCKET_STATES.closed){
      callback()
      return
    }

    setTimeout(() => {
      this.waitForSocketClosed(callback, tries + 1)
    }, 150 * tries)
  }

  onConnClose(event){
    let closeCode = event && event.code
    if(this.hasLogger()) this.log("transport", "close", event)
    this.triggerChanError()
    this.clearHeartbeats()
    if(!this.closeWasClean && closeCode !== 1000){
      this.reconnectTimer.scheduleTimeout()
    }
    this.stateChangeCallbacks.close.forEach(([, callback]) => callback(event))
  }

  /**
   * @private
   */
  onConnError(error){
    if(this.hasLogger()) this.log("transport", error)
    let transportBefore = this.transport
    let establishedBefore = this.establishedConnections
    this.stateChangeCallbacks.error.forEach(([, callback]) => {
      callback(error, transportBefore, establishedBefore)
    })
    if(transportBefore === this.transport || establishedBefore > 0){
      this.triggerChanError()
    }
  }

  /**
   * @private
   */
  triggerChanError(){
    this.channels.forEach(channel => {
      if(!(channel.isErrored() || channel.isLeaving() || channel.isClosed())){
        channel.trigger(CHANNEL_EVENTS.error)
      }
    })
  }

  /**
   * @returns {string}
   */
  connectionState(){
    switch(this.conn && this.conn.readyState){
      case SOCKET_STATES.connecting: return "connecting"
      case SOCKET_STATES.open: return "open"
      case SOCKET_STATES.closing: return "closing"
      default: return "closed"
    }
  }

  /**
   * @returns {boolean}
   */
  isConnected(){ return this.connectionState() === "open" }

  /**
   * @private
   *
   * @param {Channel}
   */
  remove(channel){
    this.off(channel.stateChangeRefs)
    this.channels = this.channels.filter(c => c.joinRef() !== channel.joinRef())
  }

  /**
   * Removes `onOpen`, `onClose`, `onError,` and `onMessage` registrations.
   *
   * @param {refs} - list of refs returned by calls to
   *                 `onOpen`, `onClose`, `onError,` and `onMessage`
   */
  off(refs){
    for(let key in this.stateChangeCallbacks){
      this.stateChangeCallbacks[key] = this.stateChangeCallbacks[key].filter(([ref]) => {
        return refs.indexOf(ref) === -1
      })
    }
  }

  /**
   * Initiates a new channel for the given topic
   *
   * @param {string} topic
   * @param {Object} chanParams - Parameters for the channel
   * @returns {Channel}
   */
  channel(topic, chanParams = {}){
    let chan = new Channel(topic, chanParams, this)
    this.channels.push(chan)
    return chan
  }

  /**
   * @param {Object} data
   */
  push(data){
    if(this.hasLogger()){
      let {topic, event, payload, ref, join_ref} = data
      this.log("push", `${topic} ${event} (${join_ref}, ${ref})`, payload)
    }

    if(this.isConnected()){
      this.encode(data, result => this.conn.send(result))
    } else {
      this.sendBuffer.push(() => this.encode(data, result => this.conn.send(result)))
    }
  }

  /**
   * Return the next message ref, accounting for overflows
   * @returns {string}
   */
  makeRef(){
    let newRef = this.ref + 1
    if(newRef === this.ref){ this.ref = 0 } else { this.ref = newRef }

    return this.ref.toString()
  }

  sendHeartbeat(){
    if(this.pendingHeartbeatRef && !this.isConnected()){ return }
    this.pendingHeartbeatRef = this.makeRef()
    this.push({topic: "phoenix", event: "heartbeat", payload: {}, ref: this.pendingHeartbeatRef})
    this.heartbeatTimeoutTimer = setTimeout(() => this.heartbeatTimeout(), this.heartbeatIntervalMs)
  }

  flushSendBuffer(){
    if(this.isConnected() && this.sendBuffer.length > 0){
      this.sendBuffer.forEach(callback => callback())
      this.sendBuffer = []
    }
  }

  onConnMessage(rawMessage){
    this.decode(rawMessage.data, msg => {
      let {topic, event, payload, ref, join_ref} = msg
      if(ref && ref === this.pendingHeartbeatRef){
        this.clearHeartbeats()
        this.pendingHeartbeatRef = null
        this.heartbeatTimer = setTimeout(() => this.sendHeartbeat(), this.heartbeatIntervalMs)
      }

      if(this.hasLogger()) this.log("receive", `${payload.status || ""} ${topic} ${event} ${ref && "(" + ref + ")" || ""}`, payload)

      for(let i = 0; i < this.channels.length; i++){
        const channel = this.channels[i]
        if(!channel.isMember(topic, event, payload, join_ref)){ continue }
        channel.trigger(event, payload, ref, join_ref)
      }

      for(let i = 0; i < this.stateChangeCallbacks.message.length; i++){
        let [, callback] = this.stateChangeCallbacks.message[i]
        callback(msg)
      }
    })
  }

  leaveOpenTopic(topic){
    let dupChannel = this.channels.find(c => c.topic === topic && (c.isJoined() || c.isJoining()))
    if(dupChannel){
      if(this.hasLogger()) this.log("transport", `leaving duplicate topic "${topic}"`)
      dupChannel.leave()
    }
  }
}


text:
These are the coding guidelines for building Apps on the Appirio Platform.

[General Coding Guidelines](general-guidelines.md)

[HTML Coding Guidelines](html-guidelines.md)

[CSS Coding Guidelines](css-guidelines.md)

[Javascript Coding Guidelines](js-guidelines.md)


text:
package org.vaadin.vol;

import org.vaadin.vol.client.ui.VYahooMapLayer;

import com.vaadin.terminal.PaintException;
import com.vaadin.terminal.PaintTarget;
import com.vaadin.ui.AbstractComponent;
import com.vaadin.ui.ClientWidget;

/**
 * Yahoo layer that can be added to {@link OpenLayersMap}.
 * <p>
  */
@ClientWidget(VYahooMapLayer.class)
public class YahooMapLayer extends AbstractComponent implements Layer {
	private String displayName;

	@Override
	public void paintContent(PaintTarget target) throws PaintException {
		super.paintContent(target);

		if(displayName != null) {
			target.addAttribute("displayName", displayName);
		}
	}

	public void setDisplayName(String displayName) {
		this.displayName = displayName;
	}

	public String getDisplayName() {
		return displayName;
	}

}


text:
<?php

namespace Migrations;

use Doctrine\DBAL\Migrations\AbstractMigration;
use Doctrine\DBAL\Schema\Schema;

/**
 * Auto-generated Migration: Please modify to your needs!
 */
class Version20170623230800 extends AbstractMigration
{
    public function getDescription()
    {
        $description = 'This is the initial migration which creates identity table.';

        return $description;
    }

    /**
     * @param Schema $schema
     */
    public function up(Schema $schema)
    {
        $table = $schema->createTable('identity');
        $table->addColumn('id', 'integer', ['autoincrement'=>true]);
        $table->addColumn('identity_type', 'integer', ['notnull'=>true, 'length'=>2]);
        $table->addColumn('name', 'string', ['notnull'=>true, 'length'=>30]);
        $table->addColumn('surname', 'string', ['notnull'=>true, 'length'=>40]);
        $table->addColumn('date_created', 'datetime', ['notnull'=>true]);
        $table->setPrimaryKey(['id']);
        $table->addOption('engine', 'InnoDB');
    }

    /**
     * @param Schema $schema
     */
    public function down(Schema $schema)
    {
        $schema->dropTable('identity');
    }
}


text:
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic;
using Thinktecture.IdentityServer.Core.Connect;
using Thinktecture.IdentityServer.Core.Models;

namespace UnitTests.Validation_Tests
{
    [TestClass]
    public class ScopeValidation
    {
        const string Category = "Scope Validation";

        List<Scope> _allScopes = new List<Scope>
            {
                new Scope
                {
                    Name = "openid",
                    Type = ScopeType.Identity
                },
                new Scope
                {
                    Name = "email",
                    Type = ScopeType.Identity
                },
                new Scope
                {
                    Name = "resource1",
                    Type = ScopeType.Resource
                },
                new Scope
                {
                    Name = "resource2",
                    Type = ScopeType.Resource
                },
            };

        Client _unrestrictedClient = new Client
            {
                ClientId = "unrestricted"
            };

        Client _restrictedClient = new Client
        {
            ClientId = "restricted",

            ScopeRestrictions = new List<string>
            {
                "openid",
                "resource1"
            }
        };

        [TestMethod]
        [TestCategory(Category)]
        public void Parse_Scopes_with_Empty_Scope_List()
        {
            var validator = new ScopeValidator();
            var scopes = validator.ParseScopes("");

            Assert.IsNull(scopes);
        }

        [TestMethod]
        [TestCategory(Category)]
        public void Parse_Scopes_with_Sorting()
        {
            var validator = new ScopeValidator();
            var scopes = validator.ParseScopes("scope3 scope2 scope1");

            Assert.AreEqual(scopes.Count, 3);

            Assert.AreEqual(scopes[0], "scope1");
            Assert.AreEqual(scopes[1], "scope2");
            Assert.AreEqual(scopes[2], "scope3");
        }

        [TestMethod]
        [TestCategory(Category)]
        public void Parse_Scopes_with_Extra_Spaces()
        {
            var validator = new ScopeValidator();
            var scopes = validator.ParseScopes("   scope3     scope2     scope1   ");

            Assert.AreEqual(scopes.Count, 3);

            Assert.AreEqual(scopes[0], "scope1");
            Assert.AreEqual(scopes[1], "scope2");
            Assert.AreEqual(scopes[2], "scope3");
        }

        [TestMethod]
        [TestCategory(Category)]
        public void Parse_Scopes_with_Duplicate_Scope()
        {
            var validator = new ScopeValidator();
            var scopes = validator.ParseScopes("scope2 scope1 scope2");

            Assert.AreEqual(scopes.Count, 2);

            Assert.AreEqual(scopes[0], "scope1");
            Assert.AreEqual(scopes[1], "scope2");
        }

        [TestMethod]
        [TestCategory(Category)]
        public void All_Scopes_Valid()
        {
            var validator = new ScopeValidator();
            var scopes = validator.ParseScopes("openid email resource1 resource2");

            var result = validator.AreScopesValid(scopes, _allScopes);

            Assert.IsTrue(result);
        }

        [TestMethod]
        [TestCategory(Category)]
        public void Invalid_Scope()
        {
            var validator = new ScopeValidator();
            var scopes = validator.ParseScopes("openid email resource1 resource2 unknown");

            var result = validator.AreScopesValid(scopes, _allScopes);

            Assert.IsFalse(result);
        }

        [TestMethod]
        [TestCategory(Category)]
        public void All_Scopes_Allowed_For_Unrestricted_Client()
        {
            var validator = new ScopeValidator();
            var scopes = validator.ParseScopes("openid email resource1 resource2");

            var result = validator.AreScopesAllowed(_unrestrictedClient, scopes);

            Assert.IsTrue(result);
        }

        [TestMethod]
        [TestCategory(Category)]
        public void All_Scopes_Allowed_For_Restricted_Client()
        {
            var validator = new ScopeValidator();
            var scopes = validator.ParseScopes("openid resource1");

            var result = validator.AreScopesAllowed(_restrictedClient, scopes);

            Assert.IsTrue(result);
        }

        [TestMethod]
        [TestCategory(Category)]
        public void Restricted_Scopes()
        {
            var validator = new ScopeValidator();
            var scopes = validator.ParseScopes("openid email resource1 resource2");

            var result = validator.AreScopesAllowed(_restrictedClient, scopes);

            Assert.IsFalse(result);
        }

        [TestMethod]
        [TestCategory(Category)]
        public void Contains_Resource_and_Identity_Scopes()
        {
            var validator = new ScopeValidator();
            var scopes = validator.ParseScopes("openid email resource1 resource2");

            var result = validator.AreScopesValid(scopes, _allScopes);

            Assert.IsTrue(result);
            Assert.IsTrue(validator.ContainsOpenIdScopes);
            Assert.IsTrue(validator.ContainsResourceScopes);
        }

        [TestMethod]
        [TestCategory(Category)]
        public void Contains_Resource_Scopes_Only()
        {
            var validator = new ScopeValidator();
            var scopes = validator.ParseScopes("resource1 resource2");

            var result = validator.AreScopesValid(scopes, _allScopes);

            Assert.IsTrue(result);
            Assert.IsFalse(validator.ContainsOpenIdScopes);
            Assert.IsTrue(validator.ContainsResourceScopes);
        }

        [TestMethod]
        [TestCategory(Category)]
        public void Contains_Identity_Scopes_Only()
        {
            var validator = new ScopeValidator();
            var scopes = validator.ParseScopes("openid email");

            var result = validator.AreScopesValid(scopes, _allScopes);

            Assert.IsTrue(result);
            Assert.IsTrue(validator.ContainsOpenIdScopes);
            Assert.IsFalse(validator.ContainsResourceScopes);
        }
    }
}


text:
package edu.ucsb.cs56.w14.drawings.zhansaya.advanced;

import java.awt.Graphics2D;
import java.awt.geom.Line2D;  // single lines
import java.awt.geom.Ellipse2D;  // ellipses and circles
import java.awt.geom.Rectangle2D; // for the bounding box
import java.awt.Rectangle;  // squares and rectangles
import java.awt.geom.GeneralPath; // combinations of lines and curves
import java.awt.geom.AffineTransform; // translation, rotation, scale
import java.awt.Shape; // general class for shapes
import java.awt.Color; // class for Colors
import java.awt.Stroke;
import java.awt.BasicStroke;

import edu.ucsb.cs56.w14.drawings.utilities.ShapeTransforms;
import edu.ucsb.cs56.w14.drawings.utilities.GeneralPathWrapper;

/**
 * A class with static methods for drawing various pictures
 *
 * @author Phill Conrad
 * @author Zhansaya Abdikarimova
 * @version for CS56, lab06, W14
 */

public class AllMyDrawings
{
    /** Draw a picture with a few Pies
     */

    public static void drawPicture1(Graphics2D g2){

	Pie p1 = new Pie(400,250,55);
	g2.setColor(Color.RED);
	g2.draw(p1);

	// Draw a Pie with apples
	ApplePie ap1 = new ApplePie(200,150,100);
	g2.setColor(new Color(0x8F00FF));
	g2.draw(ap1);
    }

    /** Draw a picture with a few Pies
     */
    public static void drawPicture2(Graphics2D g2){

	Pie p1 = new Pie(100,250,75);
	g2.setColor(Color.RED);
	g2.draw(p1);

	// Make a green Pie that's half the size,
	// and moved over 150 pixels in x direction
	Shape p2 = ShapeTransforms.scaledCopyOfLL(p1,0.5,0.5);
	p2 = ShapeTransforms.translatedCopyOf(p2,150,0);
	g2.setColor(Color.GREEN);
	g2.draw(p2);

	// Here's a Pie that's 3x as big (2x the original)
	// and moved over 150 more pixels to right.
	p2 = ShapeTransforms.scaledCopyOfLL(p2,3,3);
	p2 = ShapeTransforms.translatedCopyOf(p2,150,0);

	// We'll draw this with a thicker stroke
	Stroke thick = new BasicStroke(4.0f, BasicStroke.CAP_BUTT,
				       BasicStroke.JOIN_BEVEL);

	Stroke orig=g2.getStroke();
	g2.setStroke(thick);
	g2.setColor(new Color(242,179,111));
	g2.draw(p2);

	// Draw two Pies with Apples
	ApplePie ap1 = new ApplePie(50,50,25);
	ApplePie ap2 = new ApplePie(300,150,100);
       	g2.draw(ap1);
	g2.setColor(new Color(0x8F0000));

	// Rotate the second Pie 45 degrees around its center.
	Shape ap3 = ShapeTransforms.rotatedCopyOf(ap2, Math.PI/4.0);
	g2.draw(ap3);
	g2.setStroke(orig);
	g2.setColor(Color.BLACK);

	g2.drawString("A bunch of simple and apple pies by Zhansaya Abdikarimova", 20,20);
    }

    /** Draw a different picture with a few pies and coffee cups
     */

    public static void drawPicture3(Graphics2D g2) {

		g2.drawString("A sample of coffee cup by Phill Conrad", 20,20);
		g2.drawString("Apple pie and created by Zhansaya Abdikarimova",20,40);

		// Draw some coffee cups
		CoffeeCup cc = new CoffeeCup(20,50,70,50);
		g2.setColor(Color.RED);   g2.draw(cc);

		// Here some simple pie and  apple pies
		Pie p1 = new Pie(125, 250, 75);
		g2.setColor(Color.CYAN);
		g2.draw(p1);

		ApplePie p2 = new ApplePie(325, 150, 100);
		g2.setColor(Color.ORANGE);
		g2.draw(p2);

    }

}


text:
<?php

namespace BenatEspina\I18nRoutingBundle;

use BenatEspina\I18nRoutingBundle\DependencyInjection\Compiler\RegistryParametersResolversPass;
use BenatEspina\I18nRoutingBundle\DependencyInjection\Compiler\SetNotFoundLocaleResolverPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Bundle\Bundle;

/**
 * @author Beñat Espiña <benatespina@gmail.com>
 */
class BenatEspinaI18nRoutingBundle extends Bundle
{
    public function build(ContainerBuilder $container)
    {
        $container->addCompilerPass(new RegistryParametersResolversPass());
        $container->addCompilerPass(new SetNotFoundLocaleResolverPass());
    }
}


text:
package sdk

type PermissionType uint

const PermissionView = PermissionType(1)
const PermissionEdit = PermissionType(2)
const PermissionAdmin = PermissionType(4)

type FolderPermission struct {
	Id             uint           `json:"id"`
	FolderId       uint           `json:"folderId"`
	Created        string         `json:"created"`
	Updated        string         `json:"updated"`
	UserId         uint           `json:"userId,omitempty"`
	UserLogin      string         `json:"userLogin,omitempty"`
	UserEmail      string         `json:"userEmail,omitempty"`
	TeamId         uint           `json:"teamId,omitempty"`
	Team           string         `json:"team,omitempty"`
	Role           string         `json:"role,omitempty"`
	Permission     PermissionType `json:"permission"`
	PermissionName string         `json:"permissionName"`
	Uid            string         `json:"uid,omitempty"`
	Title          string         `json:"title,omitempty"`
	Slug           string         `json:"slug,omitempty"`
	IsFolder       bool           `json:"isFolder"`
	Url            string         `json:"url,omitempty"`
}


text:
package org.apache.hadoop.yarn;

import org.apache.hadoop.classification.InterfaceAudience.Private;
import org.apache.hadoop.classification.InterfaceStability.Unstable;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.yarn.conf.ConfigurationProvider;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.hadoop.yarn.exceptions.YarnException;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

@Private
@Unstable
public class LocalConfigurationProvider extends ConfigurationProvider {

  @Override
  public InputStream getConfigurationInputStream(Configuration bootstrapConf,
      String name) throws IOException, YarnException {
    if (name == null || name.isEmpty()) {
      throw new YarnException(
          "Illegal argument! The parameter should not be null or empty");
    } else if (YarnConfiguration.RM_CONFIGURATION_FILES.contains(name)) {
      return bootstrapConf.getConfResourceAsInputStream(name);
    }
    return new FileInputStream(name);
  }

  @Override
  public void initInternal(Configuration bootstrapConf) throws Exception {
    // Do nothing
  }

  @Override
  public void closeInternal() throws Exception {
    // Do nothing
  }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Stud. Mycol. 48: 40 (2003)

#### Original name
Hypocrea candida P. Chaverri & Samuels

### Remarks
null


text:
START_DATE=$(awsinfo_date +%Y-%m-01)
END_DATE=$(awsinfo_date --date="$START_DATE +1 month" +%Y-%m-%d)

awscli ce get-cost-and-usage --time-period Start=$START_DATE,End=$END_DATE --granularity MONTHLY --metrics BLENDED_COST UNBLENDED_COST AMORTIZED_COST NET_AMORTIZED_COST NET_UNBLENDED_COST USAGE_QUANTITY NORMALIZED_USAGE_AMOUNT --output table --query "ResultsByTime[0].Total.[
    {\"1.Name\":'AmortizedCost',\"2.Amount\":AmortizedCost.Amount,\"3.Unit\":AmortizedCost.Unit},
    {\"1.Name\":'NetAmortizedCost',\"2.Amount\":NetAmortizedCost.Amount,\"3.Unit\":NetAmortizedCost.Unit},
    {\"1.Name\":'BlendedCost',\"2.Amount\":BlendedCost.Amount,\"3.Unit\":BlendedCost.Unit},
    {\"1.Name\":'UnblendedCost',\"2.Amount\":UnblendedCost.Amount,\"3.Unit\":UnblendedCost.Unit},
    {\"1.Name\":'NetUnblendedCost',\"2.Amount\":NetUnblendedCost.Amount,\"3.Unit\":NetUnblendedCost.Unit},
    {\"1.Name\":'NormalizedUsageAmount',\"2.Amount\":NormalizedUsageAmount.Amount,\"3.Unit\":''},
    {\"1.Name\":'UsageQuantity',\"2.Amount\":UsageQuantity.Amount,\"3.Unit\":''}
    ]
    "


text:
package edu.uci.ics.pregelix.dataflow;

import java.io.DataInput;
import java.io.DataInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Writable;

import edu.uci.ics.hyracks.api.context.IHyracksTaskContext;
import edu.uci.ics.hyracks.api.dataflow.IOperatorNodePushable;
import edu.uci.ics.hyracks.api.dataflow.value.IRecordDescriptorProvider;
import edu.uci.ics.hyracks.api.exceptions.HyracksDataException;
import edu.uci.ics.hyracks.api.job.JobSpecification;
import edu.uci.ics.hyracks.dataflow.common.comm.io.FrameTupleAccessor;
import edu.uci.ics.hyracks.dataflow.common.comm.util.ByteBufferInputStream;
import edu.uci.ics.hyracks.dataflow.std.base.AbstractSingleActivityOperatorDescriptor;
import edu.uci.ics.hyracks.dataflow.std.base.AbstractUnaryInputSinkOperatorNodePushable;
import edu.uci.ics.pregelix.api.graph.GlobalAggregator;
import edu.uci.ics.pregelix.api.util.BspUtils;
import edu.uci.ics.pregelix.dataflow.base.IConfigurationFactory;
import edu.uci.ics.pregelix.dataflow.std.base.IRecordDescriptorFactory;
import edu.uci.ics.pregelix.dataflow.util.IterationUtils;

public class FinalAggregateOperatorDescriptor extends AbstractSingleActivityOperatorDescriptor {
    private static final long serialVersionUID = 1L;

    private final IConfigurationFactory confFactory;
    private final String jobId;
    private final IRecordDescriptorFactory inputRdFactory;

    public FinalAggregateOperatorDescriptor(JobSpecification spec, IConfigurationFactory confFactory,
            IRecordDescriptorFactory inputRdFactory, String jobId) {
        super(spec, 1, 0);
        this.confFactory = confFactory;
        this.jobId = jobId;
        this.inputRdFactory = inputRdFactory;
    }

    @Override
    @SuppressWarnings("rawtypes")
    public IOperatorNodePushable createPushRuntime(final IHyracksTaskContext ctx,
            IRecordDescriptorProvider recordDescProvider, int partition, int nPartitions) throws HyracksDataException {
        return new AbstractUnaryInputSinkOperatorNodePushable() {
            private final Configuration conf = confFactory.createConfiguration(ctx);
            private final List<GlobalAggregator> aggregators = BspUtils.createGlobalAggregators(conf);
            private final List<String> aggregateClassNames = Arrays.asList(BspUtils.getGlobalAggregatorClassNames(conf));
            private final FrameTupleAccessor accessor = new FrameTupleAccessor(ctx.getFrameSize(),
                    inputRdFactory.createRecordDescriptor(ctx));
            private final ByteBufferInputStream inputStream = new ByteBufferInputStream();
            private final DataInput input = new DataInputStream(inputStream);
            private final List<Writable> partialAggregateValues = BspUtils.createFinalAggregateValues(conf);

            @Override
            public void open() throws HyracksDataException {
                for (GlobalAggregator aggregator : aggregators) {
                    aggregator.init();
                }
            }

            @SuppressWarnings("unchecked")
            @Override
            public void nextFrame(ByteBuffer buffer) throws HyracksDataException {
                accessor.reset(buffer);
                int tupleCount = accessor.getTupleCount();
                try {
                    for (int i = 0; i < tupleCount; i++) {
                        // iterate over all the aggregators
                        for (int j = 0; j < partialAggregateValues.size(); j++) {
                            int start = accessor.getFieldSlotsLength() + accessor.getTupleStartOffset(i)
                                    + accessor.getFieldStartOffset(i, j);
                            inputStream.setByteBuffer(buffer, start);
                            partialAggregateValues.get(j).readFields(input);
                            aggregators.get(j).step(partialAggregateValues.get(j));
                        }
                    }
                } catch (Exception e) {
                    throw new HyracksDataException(e);
                }
            }

            @Override
            public void fail() throws HyracksDataException {

            }

            @SuppressWarnings("unchecked")
            @Override
            public void close() throws HyracksDataException {
                try {
                    List<Writable> aggValues = new ArrayList<Writable>();
                    // iterate over hdfs spilled aggregates
                    FileSystem dfs = FileSystem.get(conf);
                    String spillingDir = BspUtils.getGlobalAggregateSpillingDirName(conf,
                            IterationUtils.getSuperstep(BspUtils.getJobId(conf), ctx));
                    Path spillPath = new Path(spillingDir);
                    if (dfs.exists(spillPath)) {
                        FileStatus[] files = dfs.listStatus(spillPath);
                        // goes into this branch only when there are spilled files
                        for (int i = 0; i < files.length; i++) {
                            FileStatus file = files[i];
                            DataInput dis = dfs.open(file.getPath());
                            for (int j = 0; j < partialAggregateValues.size(); j++) {
                                GlobalAggregator aggregator = aggregators.get(j);
                                Writable partialAggregateValue = partialAggregateValues.get(j);
                                partialAggregateValue.readFields(dis);
                                aggregator.step(partialAggregateValue);
                            }
                        }
                    }
                    for (int j = 0; j < partialAggregateValues.size(); j++) {
                        GlobalAggregator aggregator = aggregators.get(j);
                        Writable finalAggregateValue = aggregator.finishFinal();
                        aggValues.add(finalAggregateValue);
                    }
                    IterationUtils.writeGlobalAggregateValue(conf, jobId, aggregateClassNames, aggValues);
                } catch (IOException e) {
                    throw new HyracksDataException(e);
                }
            }

        };
    }
}


text:
<?php

namespace CATIA\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    /**
     * The application's global HTTP middleware stack.
     *
     * These middleware are run during every request to your application.
     *
     * @var array
     */
    protected $middleware = [
        \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
    ];

    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            \CATIA\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \CATIA\Http\Middleware\VerifyCsrfToken::class,
        ],

        'api' => [
            'throttle:60,1',
        ],
    ];

    /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
        'auth' => \CATIA\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'can' => \Illuminate\Foundation\Http\Middleware\Authorize::class,
        'guest' => \CATIA\Http\Middleware\RedirectIfAuthenticated::class,
        'admin' => \CATIA\Http\Middleware\AdminMiddleware::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    ];
}


text:
namespace phi {
class DenseTensor;
}  // namespace phi

namespace paddle {
namespace framework {
namespace details {
ScaleLossGradOpHandle::ScaleLossGradOpHandle(ir::Node *node,
                                             size_t num_dev,
                                             Scope *scope,
                                             platform::Place place,
                                             platform::DeviceContext *dev_ctx,
                                             proto::VarType::Type dtype)
    : OpHandleBase(node),
      coeff_(static_cast<float>(1.0 / num_dev)),
      scope_(scope),
      place_(place),
      out_dtype_(dtype) {
  this->SetDeviceContext(place_, dev_ctx);
}

ScaleLossGradOpHandle::~ScaleLossGradOpHandle() {}

struct ScaleLossGradFunctor {
  float coeff_;
  phi::DenseTensor *out_;
  platform::Place place_;
  proto::VarType::Type out_dtype_;
  platform::DeviceContext *ctx_;

  ScaleLossGradFunctor(float coeff,
                       phi::DenseTensor *out,
                       platform::Place place,
                       proto::VarType::Type dtype,
                       platform::DeviceContext *ctx)
      : coeff_(coeff), out_(out), place_(place), out_dtype_(dtype), ctx_(ctx) {}

  template <typename OutT>
  void apply() const {
    auto *out_data = out_->mutable_data<OutT>(place_);
    if (platform::is_cpu_place(place_)) {
      *out_data = static_cast<OutT>(coeff_);
    } else if (platform::is_xpu_place(place_)) {
#if defined(PADDLE_WITH_XPU)
      OutT cast_coeff = static_cast<OutT>(coeff_);
      memory::Copy(place_,
                   out_data,
                   platform::CPUPlace(),
                   &cast_coeff,
                   SizeOfType(out_dtype_));
      VLOG(10) << place_ << "RUN Scale loss grad op";
#else
      PADDLE_THROW(platform::errors::PermissionDenied(
          "Paddle can't use XPU device since it's not compiled with XPU,"
          "Please recompile or reinstall Paddle with XPU support."));
#endif
    } else {
#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
      OutT cast_coeff = static_cast<OutT>(coeff_);
      auto stream = static_cast<phi::GPUContext *>(ctx_)->stream();
      memory::Copy(place_,
                   out_data,
                   platform::CPUPlace(),
                   &cast_coeff,
                   SizeOfType(out_dtype_),
                   stream);
      VLOG(10) << place_ << "RUN Scale loss grad op";
#else
      PADDLE_THROW(platform::errors::PermissionDenied(
          "Paddle can't use CUDA device since it's not compiled with CUDA,"
          "Please recompile or reinstall Paddle with GPU support."));
#endif
    }
  }
};

std::string ScaleLossGradOpHandle::LossGradName() const {
  return static_cast<VarHandle *>(this->outputs_[0])->name();
}

void ScaleLossGradOpHandle::RunImpl() {
  platform::RecordEvent record_event(
      Name(), platform::TracerEventType::UserDefined, 2);

  RunOnVar(local_exec_scopes_[0]->FindVar(LossGradName()), true);
}

void ScaleLossGradOpHandle::RunOnVar(Variable *var, bool record_event) {
  auto *tensor = var->GetMutable<phi::DenseTensor>();
  tensor->Resize(phi::make_ddim({1}));

#if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP)
  ScaleLossGradFunctor func(
      coeff_, tensor, place_, out_dtype_, this->dev_ctxes_.at(place_));
  if (record_event) {
    this->RunAndRecordEvent(
        [&] { framework::VisitDataType(out_dtype_, func); });
  } else {
    framework::VisitDataType(out_dtype_, func);
  }
#else
  ScaleLossGradFunctor func(coeff_, tensor, place_, out_dtype_, nullptr);
  framework::VisitDataType(out_dtype_, func);
#endif
}

std::string ScaleLossGradOpHandle::Name() const { return "ScaleLossGrad"; }
}  // namespace details
}  // namespace framework
}  // namespace paddle


text:
import Marionette from 'backbone.marionette';
import moment from 'moment';

export const SetView = Marionette.View.extend({
  tagName: 'li',
  className: 'list-group-item',
  template: require('../templates/exercises/set.html'),

  templateContext: function() {
    return {
      isFirstDate: (workout_date) =>
        this.getOption('firstDate') === moment(workout_date).format('YYYY-MM-DD'),
      formatDate: () => this.model.formatDate()
    };
  }
});

export const SetListView = Marionette.CollectionView.extend({
  tagName: 'ol',
  className: 'list-group',
  childView: SetView,

  childViewOptions: function() {
    const first = this.collection.at(0);
    let firstDate = null;
    if (first) {
      firstDate = moment(first.get('workout_date')).format('YYYY-MM-DD');
    }

    return {
      firstDate: firstDate
    };
  }
});


text:
using System;
using Tramchester.App.ViewModels;
using Tramchester.App.Models;
using System.Collections.Generic;
using Tramchester.App.Services;
using Xamarin.Geolocation;
using System.Threading.Tasks;

namespace Tramchester.App.ViewModels
{
	public class TramstopsViewModel : BaseViewModel
	{
		private ITramsService tramsService;

		List<Tramstop> tramstops;
		public List<Tramstop> Tramstops {
			get {
				return tramstops;
			}
			set {
				tramstops = value;
				this.RaiseChanged (() => this.Tramstops);
			}
		}

		public TramstopsViewModel (ITramsService tramsService)
		{
			this.tramsService = tramsService;

			var locator = new Geolocator { DesiredAccuracy = 50 };
			locator.GetPositionAsync (timeout: 10000).ContinueWith (t => {
				this.GetNearbyTramStops(t.Result.Latitude, t.Result.Longitude);
			}, TaskScheduler.FromCurrentSynchronizationContext());
		}

		private async void GetNearbyTramStops(double latitude, double longitude)
		{
			this.Tramstops = await this.tramsService.GetNearbyTramstops (latitude, longitude);
		}
	}
}


text:
<?php

?>
<?php include '../../common/view/m.header.html.php';?>

      <?php foreach($config->mobile->todoBar as $period):?>
      <?php $active = $type == $period ? 'ui-btn-active' : ''?>

<?php echo html::a($this->createLink('my', 'todo', "type=$period"), $lang->todo->periods[$period], '', "class='$active' data-theme='d'")?>

      <?php endforeach;?>

<?php $this->session->set('todoType', $type);?>
<?php foreach($todos as $todo):?>
<?php if(!$todo->private or ($todo->private and $todo->account == $app->user->account)):?>

    <h1 onClick="showDetail('todo', <?php echo $todo->id;?>)"><?php echo $todo->name;?>

<?php echo $todo->desc;?>

    <div id='item<?php echo $todo->id;?>'><?php echo $todo->desc;?>

      <?php
      common::printIcon('todo', 'finish', "id=$todo->id", $todo, 'button', '', 'hiddenwin');
      if($todo->account == $app->user->account)
      {
          if($type != 'today') common::printIcon('todo', 'import2Today',   "todoID=$todo->id");
          common::printIcon('todo', 'delete', "todoID=$todo->id", '', 'button', '', 'hiddenwin');
      }
      ?>

    <?php if(end($todos) == $todo) echo "
";?>

<?php endif;?>
<?php endforeach;?>
<?php echo $pager->show('left', 'mobile')?>

<?php echo html::a($this->createLink('todo', 'batchCreate'), $lang->todo->create, '', "data-icon='plus' data-theme='e'")?>

<?php include '../../common/view/m.footer.html.php';?>


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>Search — phase-currentcost 1.0.2 documentation</title>

  <link href='https://fonts.googleapis.com/css?family=Lato:400,700|Roboto+Slab:400,700|Inconsolata:400,700' rel='stylesheet' type='text/css'>

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

    <link rel="top" title="phase-currentcost 1.0.2 documentation" href="index.html"/>

         phase-currentcost

  <form id ="rtd-search-form" class="wy-form" action="#" method="get">
    <input type="text" name="q" placeholder="Search docs" />
    <input type="hidden" name="check_keywords" value="yes" />
    <input type="hidden" name="area" value="default" />
  </form>

phase-currentcost

Installation

Usage

Examples

Message send through RabbitMQ

Contribute

License

Modules

Workflow

Test plan

Utils module

RabbitMQ_messager module

Todo

Changelog

phase-currentcost (v1.0.2) stable; urgency=low

phase-currentcost (v1.0.1) stable; urgency=low

phase-currentcost (v1.0.0) stable; urgency=low

phase-currentcost (v0.9.17) stable; urgency=low

phase-currentcost (v0.9.16) stable; urgency=low

phase-currentcost (v0.9.15) stable; urgency=low

phase-currentcost (v0.9.14) stable; urgency=low

phase-currentcost (v0.9.13) stable; urgency=low

phase-currentcost (v0.9.12) stable; urgency=low

phase-currentcost (v0.9.11) stable; urgency=low

phase-currentcost (v0.9.10) stable; urgency=low

phase-currentcost (v0.9.9) stable; urgency=low

phase-currentcost (v0.9.8) stable; urgency=low

phase-currentcost (v0.9.7) stable; urgency=low

phase-currentcost (v0.9.6) stable; urgency=low

phase-currentcost (v0.9.5) stable; urgency=low

phase-currentcost (v0.9.4) stable; urgency=low

phase-currentcost (v0.9.3) stable; urgency=low

phase-currentcost (v0.9.2) stable; urgency=low

phase-currentcost (v0.9.1) stable; urgency=low

phase-currentcost (v0.9.0) stable; urgency=low

phase-currentcost (v0.8.0) unstable; urgency=low

phase-currentcost (v0.7.0) unstable; urgency=low

phase-currentcost (v0.6.0) unstable; urgency=low

phase-currentcost (v0.5.0) unstable; urgency=low

phase-currentcost (v0.4.1) unstable; urgency=low

phase-currentcost (v0.4.0) unstable; urgency=low

phase-currentcost (v0.3.9) unstable; urgency=low

phase-currentcost (v0.3.8) unstable; urgency=low

phase-currentcost (v0.3.7) unstable; urgency=low

phase-currentcost (v0.3.6) unstable; urgency=low

phase-currentcost (v0.3.5) unstable; urgency=low

phase-currentcost (v0.3.4) unstable; urgency=low

phase-currentcost (v0.3.3) unstable; urgency=low

phase-currentcost (v0.3.2) unstable; urgency=low

phase-currentcost (v0.3.1) unstable; urgency=low

phase-currentcost (v0.3.0) unstable; urgency=low

phase-currentcost (v0.2.3) unstable; urgency=low

phase-currentcost (v0.2.2) unstable; urgency=low

phase-currentcost (v0.2.1) unstable; urgency=low

phase-currentcost (v0.2.0) unstable; urgency=low

phase-currentcost (v0.1.10) unstable; urgency=low

phase-currentcost (v0.1.9) unstable; urgency=low

phase-currentcost (v0.1.8) unstable; urgency=low

phase-currentcost (v0.1.7) unstable; urgency=low

phase-currentcost (v0.1.6) unstable; urgency=low

phase-currentcost (v0.1.5) unstable; urgency=low

phase-currentcost (v0.1.4) unstable; urgency=low

phase-currentcost (v0.1.3) unstable; urgency=low

        phase-currentcost

Docs »

      Please activate JavaScript to enable the search
      functionality.

        © Copyright 2014, Pierre Leray.

  Sphinx theme provided by Read the Docs


text:
package org.wit.ff.ps;

import org.wit.ff.ps.serialize.ProtoStuffSerializer;

import java.util.Arrays;

public class SerializerTest {

    public static void main(String[] args) {
        ProtoStuffSerializer<String> ser = new ProtoStuffSerializer<String>();
        byte[] data = ser.serialize("我爱我家");
        System.out.println(Arrays.toString(data));
        System.out.println(ser.deserialize(data, String.class));
    }

}