text:
const path = require('path');
const fs = require('fs');
const gulp = require('gulp');
const mocha = require('gulp-mocha');
const { execSync } = require('child_process');
const packageJson = require('../package.json');

const { PROJECT_ROOT, DIST_ABSOLUTE_PATH } = require('./gulp.constants');

const npmPublish = (tag) => (done) => {
    if (!tag) {
        const tagIndex = process.argv.indexOf('--tag');

        if (tagIndex === -1) {
            throw new TypeError('Tag should be specified!');
        }

        tag = process.argv[tagIndex + 1];

        if (typeof(tag) !== 'string') {
            throw new TypeError('Tag argument should be string!');
        }

        if (TAGS_LIST.indexOf(tag) === -1 ) {
            throw new TypeError(`Unknown tag value! Tag can be one from follow: ${TAG_LATEST}.`);
        }
    }

    const tarbalFilePath = path.resolve(DIST_ABSOLUTE_PATH, `${packageJson.name}-${packageJson.version}.tgz`);

    try {
        execSync(`npm publish ${tarbalFilePath} --tag ${tag}`, { cwd: PROJECT_ROOT });
        done();
    } catch(err) {
        done(err);
    }
};

const TAG_LATEST = 'latest';
const TAG_DEV = 'dev';
const TAG_STABLE = 'stable';
const TAG_BETA = 'beta';
const TAG_CANARY = 'canary';

const TAGS_LIST = [
    TAG_LATEST,
    TAG_DEV,
    TAG_STABLE,
    TAG_BETA,
    TAG_CANARY
];

module.exports = (gulp) => {
    gulp.task('publish', npmPublish());
};


text:
import { Component, OnInit } from '@angular/core';
import {ActivatedRoute} from "@angular/router";
import {Http, Response} from "@angular/http";
import {MasterURLService} from "../services/master-url.service";
import {NgForm} from "@angular/forms";

@Component({
  selector: 'app-grupo',
  templateUrl: './grupo.component.html',
  styleUrls: ['./grupo.component.css']
})
export class GrupoComponent implements OnInit {
  title="Crear Grupo";
  subtitle="Lista de Grupos";
  private _parametros:any;
  grupos=[];
  nuevoGrupo={};
  disabledButtons={
    NuevoGrupoFormSubmitButton:false
  };

  constructor(private _ActivateRoute:ActivatedRoute, private _http:Http, private _masterURL:MasterURLService) { }

  ngOnInit() {
    this._ActivateRoute.params.subscribe(parametros=>{
      this._parametros=parametros;
      this._http.get(this._masterURL.url+'Grupo?idMateria='+this._parametros.idMateria).subscribe(
        (res:Response)=>{
          this.grupos=res.json().map((value)=>{
            value.formularioCerrado=true;
            return value;
          });
        },
        (err)=>{
          console.log(err);
        }
      )
    })
  }

  crearGrupo(formulario:NgForm){
    this.disabledButtons.NuevoGrupoFormSubmitButton=true;
    let grupo={
      nombreGrupo:formulario.value.nombreGrupo,
      numeroMaximoEstudiante:formulario.value.numeroMaximoEstudiante,
      idMateria:this._parametros.idMateria
    };
    this._http.post(this._masterURL.url+'Grupo',grupo).subscribe(
      (res:Response)=>{
        this.grupos.push(res.json());
        this.nuevoGrupo={};
        this.disabledButtons.NuevoGrupoFormSubmitButton=false;
      },
      (err)=>{
        console.log(err);
      }
    )
  }

  borrarGrupo(id:number){
    this._http.delete(this._masterURL.url+'Grupo/'+id).subscribe(
      (res)=>{
        let grupoBorrado=res.json();
        this.grupos=this.grupos.filter(value=>grupoBorrado.id!=value.id);
      },
      (err)=>{
        console.log(err);
      }
    );
  }

  actualizarGrupo(grupo:any, id:number){
    let parametros={
      nombreGrupo:grupo.nombreGrupo,
      numeroMaximoEstudiante:grupo.numeroMaximoEstudiante

    };
    this._http.put(this._masterURL.url+"Grupo/"+id,parametros).subscribe(
      (res:Response)=>{
        grupo.formularioCerrado=!grupo.formularioCerrado;
        console.log("Respuesta:",res.json());
      },
      (err) => {
        console.log("Error: ", err);
      }
    );
  }

}

redpajama_set_name: RedPajamaGithub


text:
from django.db import migrations

class Migration(migrations.Migration):

    dependencies = [
        ('forum', '0014_auto_20180927_2204'),
        ('forum', '0015_thread_originalpost'),
    ]

    operations = [
    ]


text:
using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Reflection;
using Newtonsoft.Json.Serialization;
using System.Linq;

namespace Eto.Serialization.Json
{
	public class NameConverter : JsonConverter
	{
		public class Info
		{
			public object Instance { get; set; }

			public PropertyInfo PropertyInfo { get; set; }

			public FieldInfo FieldInfo { get; set; }

			public void SetValue(object value)
			{
				if (PropertyInfo != null)
					PropertyInfo.SetValue(Instance, value, null);
				else
					FieldInfo.SetValue(Instance, value);
			}
		}

		public class ValueProvider : IValueProvider
		{
			public void SetValue(object target, object value)
			{
				var info = value as Info;
				if (info != null)
					info.SetValue(target);
			}

			public object GetValue(object target)
			{
				return null;
			}
		}

		public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
		{
			throw new NotImplementedException();
		}

		public override object ReadJson(Newtonsoft.Json.JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
		{
			var obj = JToken.ReadFrom(reader);
			var id = (string)obj;
			var binder = serializer.Binder as EtoBinder;
			if (binder != null)
			{
				var instance = binder.Instance;
				if (instance != null)
				{
					var instanceType = instance.GetType();

					var property = instanceType.GetRuntimeProperties().FirstOrDefault(r => r.Name == id);
					if (property != null)
						return new Info
						{
							PropertyInfo = property,
							Instance = instance
						};

					var field = instanceType.GetRuntimeFields().FirstOrDefault(r => r.Name == id);
					if (field != null)
						return new Info
						{
							FieldInfo = field,
							Instance = instance
						};
				}
			}
			return null;
		}

		public override bool CanConvert(Type objectType)
		{
			return true;
		}
	}
}


text:
标签

Example

Example heading New

Example heading New

Example heading New

Example heading New

Example heading New

Example heading New

{% highlight html %}

Example heading New

{% endhighlight %}

不同样式

    Default
    Primary
    Success
    Info
    Warning
    Danger

{% highlight html %}
Default
Primary
Success
Info
Warning
Danger
{% endhighlight %}


text:
<ng-template #templateref let-cellvalue="cellvalue" let-rowvalue="rowvalue">
  <div class="o-table-cell-editor-email o-table-cell-editor" [formGroup]="formGroup">
    <mat-form-field floatLabel="never" cdkFocusInitial>
      <input #input matInput type="email" [email]="true" [placeholder]="getPlaceholder()" [formControl]="formControl" [id]="cellEditorId"
        [required]="orequired">
      <mat-error *oMatError="hasError('required')">
        {{ 'FORM_VALIDATION.REQUIRED' | oTranslate }}
      </mat-error>
      <mat-error *oMatError="hasError('email')">
        {{ 'FORM_VALIDATION.EMAIL_FORMAT' | oTranslate }}
      </mat-error>
      <mat-error *ngFor="let oError of getActiveOErrors()">
        {{ getErrorText(oError) }}
      </mat-error>
    </mat-form-field>
  </div>
</ng-template>


text:
"""
dj-stripe Product model tests
"""

from copy import deepcopy

import pytest
import stripe

from djstripe.models import Product
from djstripe.models.core import Price

from . import (
    FAKE_FILEUPLOAD_ICON,
    FAKE_PLATFORM_ACCOUNT,
    FAKE_PRICE,
    FAKE_PRICE_METERED,
    FAKE_PRICE_ONETIME,
    FAKE_PRICE_TIER,
    FAKE_PRODUCT,
)

pytestmark = pytest.mark.django_db

class TestProduct:

    #
    # Helper Methods for monkeypatching
    #
    def mock_file_retrieve(*args, **kwargs):
        return deepcopy(FAKE_FILEUPLOAD_ICON)

    def mock_account_retrieve(*args, **kwargs):
        return deepcopy(FAKE_PLATFORM_ACCOUNT)

    def mock_product_get(self, *args, **kwargs):
        return deepcopy(FAKE_PRODUCT)

    @pytest.mark.parametrize("count", [1, 2, 3])
    def test___str__(self, count, monkeypatch):
        def mock_price_get(*args, **kwargs):
            return random_price_data

        # monkeypatch stripe.Product.retrieve and stripe.Price.retrieve calls to return
        # the desired json response.
        monkeypatch.setattr(stripe.Product, "retrieve", self.mock_product_get)
        monkeypatch.setattr(stripe.Price, "retrieve", mock_price_get)

        product = Product.sync_from_stripe_data(deepcopy(FAKE_PRODUCT))

        PRICE_DATA_OPTIONS = [
            deepcopy(FAKE_PRICE),
            deepcopy(FAKE_PRICE_TIER),
            deepcopy(FAKE_PRICE_METERED),
            deepcopy(FAKE_PRICE_ONETIME),
        ]
        for _ in range(count):
            random_price_data = PRICE_DATA_OPTIONS.pop()
            price = Price.sync_from_stripe_data(random_price_data)

        if count > 1:
            assert f"{FAKE_PRODUCT['name']} ({count} prices)" == str(product)
        else:
            assert f"{FAKE_PRODUCT['name']} ({price.human_readable_price})" == str(
                product
            )

    def test_sync_from_stripe_data(self, monkeypatch):

        # monkeypatch stripe.Product.retrieve call to return
        # the desired json response.
        monkeypatch.setattr(stripe.Product, "retrieve", self.mock_product_get)
        product = Product.sync_from_stripe_data(deepcopy(FAKE_PRODUCT))

        assert product.id == FAKE_PRODUCT["id"]
        assert product.name == FAKE_PRODUCT["name"]
        assert product.type == FAKE_PRODUCT["type"]


text:
class SystemHotkey {
public:
    explicit SystemHotkey(void);
    ~SystemHotkey();

    void addKey(int keyID, UINT holdKey, char charKey);
    void removeKey(int keyID);

    void beginHotkeys(void);
    void haltHotkeys(void);

public:

private:
    void listen(void);
    void run(int pos);

    bool running;
    MSG msg;
    std::vector<int> hotkeys;
};

#endif // SYSTEMHOTKEY_H


text:
import AbstractCommand from 'abstract-command';

class PaddingCommand extends AbstractCommand {
  constructor({ direction = 'auto', delta = 50, max = 200, min = 0 } = {}, root = document.documentElement, doc: Document = root.ownerDocument) {
    super(doc);
    this.direction = direction;
    this.delta = delta;
    this.max = max;
    this.min = min;
    this.root = root;
    this.document = doc;
  }

  _getProp(paragraph) {
    let direction = this.direction;

    // TODO: properly handle LTR here
    if (direction == 'auto') {
      direction = 'left';
    }

    return `padding-${direction}`;
  }

  _setPadding(paragraph, padding) {
    let value = `${padding}px`;
    let prop = this._getProp(paragraph);

    // attempt to clear padding in inline style and check if the computed
    // value matches the desired padding. If it does, keep it blank, since
    // the padding specified on the stylesheet is the correct one.
    paragraph.style[prop] = '';
    let style = window.getComputedStyle(paragraph);
    if (style[prop] == value) return;

    paragraph.style[prop] = value;
  }

  _getPadding(paragraph) {
    let prop = this._getProp(paragraph);
    let padding = paragraph.style[prop];
    if (padding && padding.match('[0-9\.]+px')) return parseInt(padding, 10);

    let style = window.getComputedStyle(paragraph);
    return parseInt(style[prop], 10) || 0;
  }

  _isParagraph(node) {
    return node.nodeName == 'P';
  }

  _findClosestOrTopmost(node) {
    while (node && node != this.root) {
      if (this._isParagraph(node)) return node;
      if (node.parentNode == this.root) return node;
      node = node.parentNode;
    }
    return null;
  }

  _findParagraphs(range) {
    let firstNode = this._findClosestOrTopmost(range.startContainer);
    let lastNode = this._findClosestOrTopmost(range.endContainer);
    if (firstNode.parentNode != lastNode.parentNode) {
      // we don't handle this case yet
      return [];
    }
    let result = [];
    for (let node = firstNode; node != lastNode; node = node.nextSibling) {
      if (this._isParagraph(node)) {
        result.push(node);
      }
    }
    if (this._isParagraph(lastNode)) {
      result.push(lastNode);
    }
    return result;
  }

  _execute(range) {
    if (!range) return;
    let paragraphs = this._findParagraphs(range);
    for (let paragraph of paragraphs) {
      let padding = this._getPadding(paragraph)
      this._setPadding(paragraph, Math.min(Math.max(padding + this.delta, this.min), this.max));
    }
  }

  _queryEnabled(range) {
    if (!range) return false;
    let paragraphs = this._findParagraphs(range);
    if (paragraphs.length == 0) return false;
    let values = paragraphs.map((paragraph) => this._getPadding(paragraph) + this.delta);
    return values.some((value) => value >= this.min && value <= this.max);
  }

  _queryState(range) {
    return false;
  }
}

export default PaddingCommand;


text:
module MountableContact
  VERSION = "0.2.1"
end


text:
package org.apache.activemq.artemis.core.server.impl.jdbc;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.function.Supplier;

import org.apache.activemq.artemis.jdbc.store.drivers.AbstractJDBCDriver;
import org.apache.activemq.artemis.jdbc.store.sql.SQLProvider;
import org.apache.activemq.artemis.utils.UUID;
import org.jboss.logging.Logger;

/**
 * JDBC implementation of a {@link SharedStateManager}.
 */
@SuppressWarnings("SynchronizeOnNonFinalField")
final class JdbcSharedStateManager extends AbstractJDBCDriver implements SharedStateManager {

   private static final Logger logger = Logger.getLogger(JdbcSharedStateManager.class);
   public static final int MAX_SETUP_ATTEMPTS = 20;
   private final String holderId;
   private final long lockExpirationMillis;
   private JdbcLeaseLock liveLock;
   private JdbcLeaseLock backupLock;
   private PreparedStatement readNodeId;
   private PreparedStatement writeNodeId;
   private PreparedStatement initializeNodeId;
   private PreparedStatement readState;
   private PreparedStatement writeState;

   public static JdbcSharedStateManager usingDataSource(String holderId,
                                                        long locksExpirationMillis,
                                                        DataSource dataSource,
                                                        SQLProvider provider) {
      final JdbcSharedStateManager sharedStateManager = new JdbcSharedStateManager(holderId, locksExpirationMillis);
      sharedStateManager.setDataSource(dataSource);
      sharedStateManager.setSqlProvider(provider);
      try {
         sharedStateManager.start();
         return sharedStateManager;
      } catch (SQLException e) {
         throw new IllegalStateException(e);
      }
   }

   public static JdbcSharedStateManager usingConnectionUrl(String holderId,
                                                           long locksExpirationMillis,
                                                           String jdbcConnectionUrl,
                                                           String jdbcDriverClass,
                                                           SQLProvider provider) {
      final JdbcSharedStateManager sharedStateManager = new JdbcSharedStateManager(holderId, locksExpirationMillis);
      sharedStateManager.setJdbcConnectionUrl(jdbcConnectionUrl);
      sharedStateManager.setJdbcDriverClass(jdbcDriverClass);
      sharedStateManager.setSqlProvider(provider);
      try {
         sharedStateManager.start();
         return sharedStateManager;
      } catch (SQLException e) {
         throw new IllegalStateException(e);
      }
   }

   @Override
   protected void createSchema() throws SQLException {
      try {
         createTable(sqlProvider.createNodeManagerStoreTableSQL(), sqlProvider.createNodeIdSQL(), sqlProvider.createStateSQL(), sqlProvider.createLiveLockSQL(), sqlProvider.createBackupLockSQL());
      } catch (SQLException e) {
         //no op: if a table already exists is not a problem in this case, the prepareStatements() call will fail right after it if the table is not correctly initialized
         if (logger.isDebugEnabled()) {
            logger.debug("Error while creating the schema of the JDBC shared state manager", e);
         }
      }
   }

   static JdbcLeaseLock createLiveLock(String holderId,
                                       Connection connection,
                                       SQLProvider sqlProvider,
                                       long expirationMillis,
                                       long maxAllowableMillisDiffFromDBtime) throws SQLException {
      return new JdbcLeaseLock(holderId, connection, connection.prepareStatement(sqlProvider.tryAcquireLiveLockSQL()), connection.prepareStatement(sqlProvider.tryReleaseLiveLockSQL()), connection.prepareStatement(sqlProvider.renewLiveLockSQL()), connection.prepareStatement(sqlProvider.isLiveLockedSQL()), connection.prepareStatement(sqlProvider.currentTimestampSQL()), expirationMillis, maxAllowableMillisDiffFromDBtime);
   }

   static JdbcLeaseLock createBackupLock(String holderId,
                                         Connection connection,
                                         SQLProvider sqlProvider,
                                         long expirationMillis,
                                         long maxAllowableMillisDiffFromDBtime) throws SQLException {
      return new JdbcLeaseLock(holderId, connection, connection.prepareStatement(sqlProvider.tryAcquireBackupLockSQL()), connection.prepareStatement(sqlProvider.tryReleaseBackupLockSQL()), connection.prepareStatement(sqlProvider.renewBackupLockSQL()), connection.prepareStatement(sqlProvider.isBackupLockedSQL()), connection.prepareStatement(sqlProvider.currentTimestampSQL()), expirationMillis, maxAllowableMillisDiffFromDBtime);
   }

   @Override
   protected void prepareStatements() throws SQLException {
      this.liveLock = createLiveLock(this.holderId, this.connection, sqlProvider, lockExpirationMillis, 0);
      this.backupLock = createBackupLock(this.holderId, this.connection, sqlProvider, lockExpirationMillis, 0);
      this.readNodeId = connection.prepareStatement(sqlProvider.readNodeIdSQL());
      this.writeNodeId = connection.prepareStatement(sqlProvider.writeNodeIdSQL());
      this.initializeNodeId = connection.prepareStatement(sqlProvider.initializeNodeIdSQL());
      this.writeState = connection.prepareStatement(sqlProvider.writeStateSQL());
      this.readState = connection.prepareStatement(sqlProvider.readStateSQL());
   }

   private JdbcSharedStateManager(String holderId, long lockExpirationMillis) {
      this.holderId = holderId;
      this.lockExpirationMillis = lockExpirationMillis;
   }

   @Override
   public LeaseLock liveLock() {
      return this.liveLock;
   }

   @Override
   public LeaseLock backupLock() {
      return this.backupLock;
   }

   private UUID rawReadNodeId() throws SQLException {
      final PreparedStatement preparedStatement = this.readNodeId;
      try (ResultSet resultSet = preparedStatement.executeQuery()) {
         if (!resultSet.next()) {
            return null;
         } else {
            final String nodeId = resultSet.getString(1);
            if (nodeId != null) {
               return new UUID(UUID.TYPE_TIME_BASED, UUID.stringToBytes(nodeId));
            } else {
               return null;
            }
         }
      }
   }

   @Override
   public UUID readNodeId() {
      synchronized (connection) {
         try {
            connection.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
            connection.setAutoCommit(true);
            final UUID nodeId = rawReadNodeId();
            return nodeId;
         } catch (SQLException e) {
            throw new IllegalStateException(e);
         }
      }
   }

   @Override
   public void writeNodeId(UUID nodeId) {
      synchronized (connection) {
         try {
            connection.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
            connection.setAutoCommit(true);
            rawWriteNodeId(nodeId);
         } catch (SQLException e) {
            throw new IllegalStateException(e);
         }
      }
   }

   private void rawWriteNodeId(UUID nodeId) throws SQLException {
      final PreparedStatement preparedStatement = this.writeNodeId;
      preparedStatement.setString(1, nodeId.toString());
      if (preparedStatement.executeUpdate() != 1) {
         throw new IllegalStateException("can't write NODE_ID on the JDBC Node Manager Store!");
      }
   }

   private boolean rawInitializeNodeId(UUID nodeId) throws SQLException {
      final PreparedStatement preparedStatement = this.initializeNodeId;
      preparedStatement.setString(1, nodeId.toString());
      final int rows = preparedStatement.executeUpdate();
      assert rows <= 1;
      return rows > 0;
   }

   @Override
   public UUID setup(Supplier<? extends UUID> nodeIdFactory) {
      SQLException lastError = null;
      synchronized (connection) {
         final UUID newNodeId = nodeIdFactory.get();
         for (int attempts = 0; attempts < MAX_SETUP_ATTEMPTS; attempts++) {
            lastError = null;
            try {
               final UUID nodeId = initializeOrReadNodeId(newNodeId);
               if (nodeId != null) {
                  return nodeId;
               }
            } catch (SQLException e) {
               if (logger.isDebugEnabled()) {
                  logger.debug("Error while attempting to setup the NodeId", e);
               }
               lastError = e;
            }
         }
      }
      if (lastError != null) {
         logger.error("Unable to setup a NodeId on the JDBC shared state", lastError);
      } else {
         logger.error("Unable to setup a NodeId on the JDBC shared state");
      }
      throw new IllegalStateException("FAILED TO SETUP the JDBC Shared State NodeId");
   }

   private UUID initializeOrReadNodeId(final UUID newNodeId) throws SQLException {
      final UUID nodeId;
      connection.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
      connection.setAutoCommit(false);
      try {
         //optimistic try to initialize nodeId
         if (rawInitializeNodeId(newNodeId)) {
            nodeId = newNodeId;
         } else {
            nodeId = rawReadNodeId();
         }
      } catch (SQLException e) {
         connection.rollback();
         connection.setAutoCommit(true);
         if (logger.isDebugEnabled()) {
            logger.debug("Rollback while trying to update NodeId to " + newNodeId, e);
         }
         return null;
      }
      if (nodeId != null) {
         connection.commit();
         connection.setAutoCommit(true);
         return nodeId;
      } else {
         //that means that the rawInitializeNodeId has failed just due to contention or the nodeId wasn't committed yet
         connection.rollback();
         connection.setAutoCommit(true);
         if (logger.isDebugEnabled()) {
            logger.debug("Rollback after failed to update NodeId to " + newNodeId + " and haven't found any NodeId");
         }
         return null;
      }
   }

   private static State decodeState(String s) {
      if (s == null) {
         return State.NOT_STARTED;
      }
      switch (s) {
         case "L":
            return State.LIVE;
         case "F":
            return State.FAILING_BACK;
         case "P":
            return State.PAUSED;
         case "N":
            return State.NOT_STARTED;
         default:
            throw new IllegalStateException("unknown state [" + s + "]");
      }
   }

   private static String encodeState(State state) {
      switch (state) {
         case LIVE:
            return "L";
         case FAILING_BACK:
            return "F";
         case PAUSED:
            return "P";
         case NOT_STARTED:
            return "N";
         default:
            throw new IllegalStateException("unknown state [" + state + "]");
      }
   }

   @Override
   public State readState() {
      synchronized (connection) {
         try {
            connection.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
            connection.setAutoCommit(true);
            final State state;
            final PreparedStatement preparedStatement = this.readState;
            try (ResultSet resultSet = preparedStatement.executeQuery()) {
               if (!resultSet.next()) {
                  state = State.FIRST_TIME_START;
               } else {
                  state = decodeState(resultSet.getString(1));
               }
            }
            return state;
         } catch (SQLException e) {
            throw new IllegalStateException(e);
         }
      }
   }

   @Override
   public void writeState(State state) {
      final String encodedState = encodeState(state);
      synchronized (connection) {
         try {
            connection.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
            connection.setAutoCommit(true);
            final PreparedStatement preparedStatement = this.writeState;
            preparedStatement.setString(1, encodedState);
            if (preparedStatement.executeUpdate() != 1) {
               throw new IllegalStateException("can't write STATE to the JDBC Node Manager Store!");
            }
         } catch (SQLException e) {
            throw new IllegalStateException(e);
         }
      }
   }

   @Override
   public void stop() throws SQLException {
      //release all the managed resources inside the connection lock
      if (sqlProvider.closeConnectionOnShutdown()) {
         synchronized (connection) {
            this.readNodeId.close();
            this.writeNodeId.close();
            this.initializeNodeId.close();
            this.readState.close();
            this.writeState.close();
            this.liveLock.close();
            this.backupLock.close();
            super.stop();
         }
      }
   }

   @Override
   public void close() throws SQLException {
      stop();
   }
}


text:
<?php

namespace AppquariumBundle\Services;

use AppquariumBundle\Aquarium\library\Upload;
use AppquariumBundle\Aquarium\Repository\EntityRepositoryInterface;
use AppquariumBundle\Entity\Aquarium;
use SimpleBus\Message\Message;

class AquariumPost
{

    private $aquarium;
    private $entityManager;
    private $uploadManager;

    public function __construct(EntityRepositoryInterface $entityManager, Aquarium $aquarium, Upload $uploadManager)
    {

        $this->aquarium = $aquarium;
        $this->entityManager = $entityManager;
        $this->uploadManager = $uploadManager;
    }

    public function store(Message $message)
    {

        if (!is_null($message->aquariumId)) {
            $this->aquarium = $this->aquariumById($message->aquariumId);
        }

        $this->uploadAvatar($message->avatar);
        $user = $this->userAquarium($message->userId);
        $this->aquarium->setAlias($message->data["alias"]);
        $this->aquarium->setCapacity($message->data["capacity"]);
        $this->aquarium->setDescription($message->data["description"]);
        $this->aquarium->setWaterType($message->data["water"]);
        $this->aquarium->setUser($user);
        $this->entityManager->save($this->aquarium);

        return $this->aquarium->getId();

    }

    public function userAquarium($userId)
    {

        $userRepository = $this->entityManager->repository("AppquariumBundle:User");
        return $userRepository->find($userId);
    }

    public function aquariumById($aquariumId)
    {

        $aquariumRepository = $this->entityManager->repository("AppquariumBundle:Aquarium");
        $aquarium = $aquariumRepository->find($aquariumId);
        if (empty($aquarium)) {
            throw new \Exception("invalid Aquarium id");
        }
        return $aquarium;

    }

    private function uploadAvatar($avatar)
    {

        if(!empty($avatar["tmp_name"])){

            $imageHashedName = $this->uploadManager->upload($avatar, "assets/dashboard/img/uploads/");
            $this->aquarium->setAvatar($imageHashedName);
        }

    }

}


text:
.class public interface abstract Lorg/apache/http/io/SessionOutputBuffer;
.super Ljava/lang/Object;
.source "SessionOutputBuffer.java"

# virtual methods
.method public abstract flush()V
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljava/io/IOException;
        }
    .end annotation
.end method

.method public abstract getMetrics()Lorg/apache/http/io/HttpTransportMetrics;
.end method

.method public abstract write(I)V
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljava/io/IOException;
        }
    .end annotation
.end method

.method public abstract write([B)V
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljava/io/IOException;
        }
    .end annotation
.end method

.method public abstract write([BII)V
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljava/io/IOException;
        }
    .end annotation
.end method

.method public abstract writeLine(Ljava/lang/String;)V
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljava/io/IOException;
        }
    .end annotation
.end method

.method public abstract writeLine(Lorg/apache/http/util/CharArrayBuffer;)V
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Ljava/io/IOException;
        }
    .end annotation
.end method


text:
'use strict'

const Keys = require('./Keys')
const Container = require('./Container')
const fs = require('fs')
const path = require('path')
const validate = require('jsonschema').validate
const semver = require('semver')

/**
 * Returns all files and folders for a given path
 * @param {String} rootPath the path of the directory you want to examine
 * @returns {Object} attribute `files` is a list of file names, attribute 'folders' is a list of folder names
 */
function split (rootPath) {
  let files = []
  let folders = []
  let result = {
    files: files,
    folders: folders
  }
  let fileNames = fs.readdirSync(rootPath)
  fileNames.forEach(fn => {
    let stat = fs.statSync(path.join(rootPath, fn))
    if (stat.isDirectory()) {
      folders.push(fn)
    } else if (stat.isFile()) {
      files.push(fn)
    }
  })
  return result
}

const validatorPattern = /^([a-z_]+)\.validators\.js$/
const schemaPattern = /^([a-z_]+)\.schema\.json$/
const migratorPattern = /^([a-z_\d.]+)\.migrator\.js$/
const formatPattern = /^([a-z_]+)-(\d+\.\d+\.\d+)$/

/**
 * Scans a set of files for validators and schemas and adds them to a given list; also scans for migrators
 * @param {String} rootPath the path prefix for `fileNames` elements
 * @param {Array<String>} fileNames list of filenames under the root path
 * @param {Array<Function>} validators output list of validator functions
 * @param {Map<String, Function>} migratorMap optional map of migrators
 * @returns {void}
 */
function scanForValidatorsAndMigrators (rootPath, fileNames, validators, migratorMap) {
  fileNames.forEach(fn => {
    // validators
    let fullFileName = path.join(rootPath, fn)
    let matchValidator = validatorPattern.exec(fn)
    if (matchValidator !== null) {
      let validator = require(fullFileName)
      validators.push(validator)
      return
    }

    // schemas
    let matchSchema = schemaPattern.exec(fn)
    if (matchSchema !== null) {
      let key = matchSchema[1]
      let schema = require(fullFileName)
      let validator = container => {
        if (!validate(container.getMetaObject(key), schema).valid) {
          throw new Error(`Meta object '${key}' is not valid!`)
        }
      }
      validators.push(validator)
      return
    }

    if (migratorMap === null) {
      return
    }

    // migrators
    let matchMigrator = migratorPattern.exec(fn)
    if (matchMigrator !== null) {
      let version = matchMigrator[1]
      let migrator = require(fullFileName)
      migratorMap.set(version, migrator)
    }
  })
}

// read in all formats and validators
const FormatCollection = {
  Validators: [],
  Formats: new Map()
}
const rootDir = split(__dirname)
scanForValidatorsAndMigrators(__dirname, rootDir.files, FormatCollection.Validators, null)
const Formats = FormatCollection.Formats
rootDir.folders.forEach(folder => {
  let Format = {
    Validators: [],
    Versions: new Map()
  }
  Formats.set(folder, Format)
  let fullFolderPath = path.join(__dirname, folder)
  let formatDir = split(fullFolderPath)
  scanForValidatorsAndMigrators(fullFolderPath, formatDir.files, Format.Validators, null)
  formatDir.folders.forEach(version => {
    if (!semver.valid(version)) {
      throw new Error(`'${version}' is not a valid semantic version!`)
    }
    let versionValidators = []
    let fullVersionFolderPath = path.join(fullFolderPath, version)
    let versionDir = split(fullVersionFolderPath)
    let migratorMap = new Map()
    scanForValidatorsAndMigrators(fullVersionFolderPath, versionDir.files, versionValidators, migratorMap)
    Format.Versions.set(version, {
      Validators: versionValidators,
      Migrators: migratorMap
    })
  })
})

/**
 * Determines the format version of a container.
 * @param {Container} container the container file
 * @returns {{name: String, version: String}} version information
 * @throws {Error} if container does not have a `model` meta object or model has no format attribute
 */
function getContainerFormatVersion (container) {
  let model = container.getMetaObject(Keys.ModelKey)
  if (model === null) {
    throw new Error(`Meta object '${Keys.ModelKey}' required!`)
  }
  let formatId = model.format
  if (!formatId) {
    throw new Error('`format` attribute required!')
  }
  let formatMatch = formatPattern.exec(formatId)
  if (formatMatch === null) {
    throw new Error('Wrong syntax for `format` attribute')
  }
  let formatName = formatMatch[1]
  let version = formatMatch[2]
  return {
    name: formatName,
    version: version
  }
}

/**
 * Throws an exception when one validator fails
 * @param {Container} container the format file
 * @returns {void}
 * @throws {Error} if one validator fails for the given container
 */
function checkContainer (container) {
  let formatVersion = getContainerFormatVersion(container)
  let formatName = formatVersion.name
  let version = formatVersion.version
  let rootValidators = FormatCollection.Validators
  if (!FormatCollection.Formats.has(formatName)) {
    throw new Error(`Unknown format '${formatName}'!`)
  }
  let Format = FormatCollection.Formats.get(formatName)
  let formatValidators = Format.Validators
  if (!Format.Versions.has(version)) {
    throw new Error(`Unknown format version '${formatName}-${version}'!`)
  }
  let Version = Format.Versions.get(version)
  let versionValidators = Version.Validators
  let validators = rootValidators.concat(formatValidators, versionValidators)
  validators.forEach(validator => validator(container))
}

/**
 * Upgrades a container to the newest format version
 * @param {Container} container the format file
 * @returns {Container} a new format file upgraded to the newest version
 */
function upgrade (container) {
  let formatVersion = getContainerFormatVersion(container)
  let formatName = formatVersion.name
  let version = formatVersion.version

  // get migrator
  if (!FormatCollection.Formats.has(formatName)) {
    throw new Error(`Unknown format '${formatName}'!`)
  }
  let Format = FormatCollection.Formats.get(formatName)
  if (!Format.Versions.has(version)) {
    return new Error(`Unknown format version '${formatName}-${version}'!`)
  }
  let Version = Format.Versions.get(version)
  let migrators = Version.Migrators
  let bestKey = version
  let bestMigrator = null
  migrators.forEach((migrator, key) => {
    if (semver.gt(key, bestKey)) {
      bestKey = key
      bestMigrator = migrator
    }
  })
  if (bestMigrator === null) {
    return container
  }
  let newContainer = bestMigrator(container)
  checkContainer(newContainer)
  return newContainer
}

/**
 * Load container from a buffer.
 * @param {Buffer} buffer the buffer containing the actual file data
 * @returns {Promise|Promise.<Container>} the loaded container
 */
function load (buffer) {
  let container = new Container()
  return container.load(buffer)
    .then(() => {
      checkContainer(container)
      return upgrade(container)
    })
}

/**
 * Saves a container file to a buffer
 * @param {Container} container the container file
 * @returns {Promise|Promise.<Buffer>} the buffer with the voxelify model file
 */
function save (container) {
  checkContainer(container)
  return container.save()
}

module.exports = {
  load: load,
  save: save
}


text:
<?xml version="1.0"?>

<!-- $Id: features.xml,v 1.3 2002/10/27 21:02:41 marcohu Exp $ -->
<!-- This file contains the Jalopy feature list -->

<!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN"
          "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd"
  [ <!ENTITY keywords SYSTEM "_keywords.xml"> ] >

<article role="docu">
<articleinfo>
<title>Jalopy - Feature list</title>
&keywords;
</articleinfo>

<sect1 id="featurelist">
<title>Feature list</title>
<itemizedlist mark="square">
<listitem>
distributed settings support - share one code convention across multiple machines/platforms
</listitem>

<listitem>
easy switching between several code conventions
</listitem>

<listitem>
several pre-configured brace styles (C, Sun, GNU), but fully user-configurable
</listitem>

<listitem>
auto-insertion/removal of obsolete braces
</listitem>

<listitem>
special empty braces handling
</listitem>

<listitem>
wide range of whitespace options for method declarations/calls, brackets, parentheses, operators, delimeters...
</listitem>

<listitem>
prepending of leading whitespace before every line
</listitem>

<listitem>
powerful indentation/alignment capabilities
</listitem>

<listitem>
configurable line wrapping
</listitem>

<listitem>
controlable amount of blank lines between certain sections, blocks, statements...
</listitem>

<listitem>
comment removal for all sorts of comments
</listitem>

<listitem>
special comments to prohibit formatting for certain pieces of code
(uses the Jindent syntax to retain backward compatibility)
</listitem>

<listitem>
auto-insertion of missing Javadoc comments (selectively configurable for the
different access levels) with variable interpolation
</listitem>

<listitem>
auto-removal/insertion/correction of obsolete/missing/wrong Javadoc standard tags
</listitem>

<listitem>
auto-insertion of parentheses around expressions to make operator precedence obvious
</listitem>

<listitem>
auto-insertion of a serial version UID for serializable classes
</listitem>

<listitem>
sorting of class/interface/variable/constructor/method declarations
</listitem>

<listitem>
sorting of access modifiers
</listitem>

<listitem>
insertion of separation comments between class/interface/variable/constructor/method declarations
</listitem>

<listitem>
insertion of custom header/footer templates at the begin/end of every file (with variable interpolation)
</listitem>

<listitem>
sorting/grouping of import declarations
</listitem>

<listitem>
import optimization: expansion of on-demand import declarations to several
single-type declarations (and vice versa). As of today only implemented for
the Ant and JBuilder Plug-in
</listitem>

<listitem>
configurable message output
</listitem>

<listitem>
numbered backups (1-30)
</listitem>

<listitem>
multi-processor support
</listitem>

<listitem>
client <ulink url="./api/index.html">API</ulink> to make integration with other tools easy
</listitem>

<listitem>
graphical application to customize the settings (with live-preview)
</listitem>

<listitem>
powerful command line interface with regular expression filtering (<ulink url="./plugins.html">Console Plug-in</ulink>)
</listitem>

<listitem>
several <ulink url="./plugins.html">Plug-ins</ulink> to integrate with common Java applications (current set includes
<ulink url="./plugin-ant.html">Ant</ulink>,
<ulink url="./plugin-eclipse.html">Eclipse</ulink>,
<ulink url="./plugin-jbuilder.html">JBuilder</ulink>,
<ulink url="./plugin-jdev.html">JDeveloper</ulink>,
<ulink url="./plugin-jedit.html">jEdit</ulink> and
<ulink url="./plugin-netbeans.html">NetBeans</ulink>/Sun ONE Studio)
</listitem>

<listitem>
"<emphasis role="bold"><ulink url="http://opensource.org/docs/certification_mark.php">OSI Certified Open Source Software</ulink></emphasis>"
 software, released under a <ulink url="./license-bsd.html">BSD License</ulink>
</listitem>

</itemizedlist>
</sect1>
</article>


text:
require 'rubygems'
require 'bundler'
require 'minitest'
require 'flexmock'
require 'flexmock/minitest'
require 'net/http'
require_relative 'http_simulator'

$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'lib'))
$LOAD_PATH.unshift(File.dirname(__FILE__))
require 'blogrpc'


text:
 #ifdef aliyun_api_ossadmin_2015_05_20_EXPORTS
 #define ALIYUN_API_OSSADMIN_2015_05_20_DLL_EXPORT_IMPORT __declspec(dllexport)
 #else
 #define ALIYUN_API_OSSADMIN_2015_05_20_DLL_EXPORT_IMPORT
 #endif
#else
#define ALIYUN_API_OSSADMIN_2015_05_20_DLL_EXPORT_IMPORT
#endif
namespace aliyun {
struct OssAdminErrorInfo {
  std::string request_id;
  std::string code;
  std::string message;
  std::string host_id;
};
class ALIYUN_API_OSSADMIN_2015_05_20_DLL_EXPORT_IMPORT OssAdmin {
public:
  static OssAdmin* CreateOssAdminClient(std::string endpoint, std::string appid, std::string secret);
  ~OssAdmin();
private:
  OssAdmin(std::string host, std::string appid, std::string secret);
public:
  void SetUseTls(bool use_tls = true) {  if(support_tls_) use_tls_ = use_tls;  }
  bool GetUseTls() {  return use_tls_;  }
  bool GetSupportTls() {  return support_tls_;  }
  void SetProxyHost(std::string proxy_host) {
    if(this->proxy_host_) {
      free(this->proxy_host_);
    }
    this->proxy_host_ = strdup(proxy_host.c_str());
  }
  std::string GetProxyHost() {  return this->proxy_host_;  }
  void SetRegionId(std::string region_id) {
    if(this->region_id_) {
      free(this->region_id_);
    }
    this->region_id_ = strdup(region_id.c_str());
  }
  std::string GetRegionId() {  return this->region_id_;  }
  int BindBucketVip(const OssAdminBindBucketVipRequestType& req,
          OssAdminBindBucketVipResponseType* resp,
          OssAdminErrorInfo* error_info);

  int CreateImgVpc(const OssAdminCreateImgVpcRequestType& req,
          OssAdminCreateImgVpcResponseType* resp,
          OssAdminErrorInfo* error_info);

  int CreateOssVpc(const OssAdminCreateOssVpcRequestType& req,
          OssAdminCreateOssVpcResponseType* resp,
          OssAdminErrorInfo* error_info);

  int DeleteImgVpc(const OssAdminDeleteImgVpcRequestType& req,
          OssAdminDeleteImgVpcResponseType* resp,
          OssAdminErrorInfo* error_info);

  int DeleteOssVpc(const OssAdminDeleteOssVpcRequestType& req,
          OssAdminDeleteOssVpcResponseType* resp,
          OssAdminErrorInfo* error_info);

  int GetBucketVips(const OssAdminGetBucketVipsRequestType& req,
          OssAdminGetBucketVipsResponseType* resp,
          OssAdminErrorInfo* error_info);

  int GetImgVpcInfo(const OssAdminGetImgVpcInfoRequestType& req,
          OssAdminGetImgVpcInfoResponseType* resp,
          OssAdminErrorInfo* error_info);

  int GetOssVpcInfo(const OssAdminGetOssVpcInfoRequestType& req,
          OssAdminGetOssVpcInfoResponseType* resp,
          OssAdminErrorInfo* error_info);

  int UnBindBucketVip(const OssAdminUnBindBucketVipRequestType& req,
          OssAdminUnBindBucketVipResponseType* resp,
          OssAdminErrorInfo* error_info);

private:
  char* appid_;
  char* secret_;
  char* version_;
  char* host_;
  char* proxy_host_;
  bool support_tls_;
  bool use_tls_;
  char* region_id_;
};  //end class
} // end namespace
#endif


text:
package corejava.lambdasone.problemthree;

public interface TwoElementPredicate<T> {
	boolean isBetter(T element1, T element2);
}


text:
class Pokemon {
    constructor(name, level) {
        this.name = name;
        this.level = level;
    }

    /**
     * Output pokemon info
     */
    show() {
        console.log(`Pokemon ${this.name}, ${this.level}lvl`);
    }

    /**
     * Returns pokemon's level
     */
    valueOf() {
        return this.level;
    }
}

class PokemonList extends Array {
    /**
     * Add Pokemon to list
     */
    add(name, level) {
        this.push(new Pokemon(name, level));
    }

    /**
     * Return pokemon with biggest level
     */
    max() {
        return this.reduce((previous, current) => {
            return current >= previous
                ? current
                : previous;
        });
    }

    /**
     * Output info for all pokemons in the list
     */
    show() {
        this.forEach(el => el.show())
        console.log(`Pokemon count: ${this.length}`);
    }
}

console.log('Creating lists....');
const lost = new PokemonList(new Pokemon('Pikachu', 2));
const found = new PokemonList(
    new Pokemon('Bulbasaur', 1),
    new Pokemon('Venusaur', 3)
);

lost.add('Charmander', 1);
lost.add('Charmeleon', 2);
found.add('Charizard', 3);

lost.show();
found.show();

console.log('Transfering pokemon....');
let transferIdx = 2;
let transferPokemon = found[transferIdx];
found.splice(transferIdx, 1);
lost.add(transferPokemon.name, transferPokemon.level);

lost.show();
found.show();

console.log('Searching pokemon with max level...');
found.max().show();
lost.max().show();


text:
package wiiz.blink.client;

import java.util.Random;

import net.minecraft.util.EnumParticleTypes;
import net.minecraft.world.World;
import net.minecraftforge.fml.client.registry.ClientRegistry;
import net.minecraftforge.fml.common.FMLCommonHandler;
import wiiz.blink.client.event.ClientEventHandler;
import wiiz.blink.common.CommonProxy;

public class ClientProxy extends CommonProxy
{

	@Override
	public void registerEvents()
	{
		ClientRegistry.registerKeyBinding(ClientEventHandler.keyBlink);
		FMLCommonHandler.instance().bus().register(new ClientEventHandler());
	}

	public void spawnParticles(World world, double posX, double posY, double posZ, double targetX, double targetY, double targetZ)
	{
		short amount = 96;

		System.out.println("PosX: " + posX + " PosY: " + posY + " PosZ: " + posZ);
		System.out.println("TargetX: " + targetX + " TargetY: " + targetY + " TargetZ: " + targetZ);

        for (int i = 0; i < amount; ++i)
        {
            double d9 = (double)i / ((double)amount - 1.0D);
            float offX = (new Random().nextFloat() - 0.5F) * 0.2F;
            float offY = (new Random().nextFloat() - 0.5F) * 0.2F;
            float offZ = (new Random().nextFloat() - 0.5F) * 0.2F;
            double xPos = posX + (targetX - posX) * d9 + (new Random().nextDouble() - 0.5D) * (double)1.9 * 2.0D;
            double yPos = posY + (targetY - posY) * d9 + new Random().nextDouble() * (double)0.9;
            double zPos = posZ + (targetZ - posZ) * d9 + (new Random().nextDouble() - 0.5D) * (double)1.9 * 2.0D;
            world.spawnParticle(EnumParticleTypes.PORTAL, xPos, yPos, zPos, (double)offX, (double)offY, (double)offZ, new int[0]);
        }
	}

}


text:
@echo off
@title delete if exist target

if exist target (
  rd /s /q target
) else (
  echo "not exist dir target"
)


text:
<!DOCTYPE html>

	<meta charset="UTF-8">
	<title>Grid System</title>
	<link rel="stylesheet" href="../build/base.css">
	<link rel="stylesheet" href="../build/grid.css">

Row

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Consequatur sint mollitia itaque reiciendis quam unde veritatis, reprehenderit earum dolorum temporibus ut provident, placeat magni minus iusto eligendi? Odit dignissimos, quisquam.

Iste culpa aliquam nostrum aliquid vitae, doloremque delectus adipisci nemo, alias sint, quos illum possimus assumenda et ad modi est officia. Adipisci rem ut, deserunt voluptatum maiores quae eum, quasi.

Exercitationem ipsum aliquam dolorum architecto neque, autem obcaecati natus, hic perferendis earum deleniti ipsa nisi fugiat similique explicabo vitae veritatis doloribus atque mollitia, incidunt dolores nam nemo laborum! Accusamus, eligendi!

Omnis voluptates excepturi architecto dignissimos nisi accusantium praesentium nesciunt deleniti velit sapiente officiis possimus rerum exercitationem vitae aperiam amet nulla dolorem molestiae mollitia quasi a ut veritatis, quos laudantium assumenda.

Quisquam perspiciatis reprehenderit fuga! Sunt laborum aliquam libero tempora quos sit quia, amet perspiciatis, velit nam dolore doloribus, reiciendis quo fugiat totam quod qui. Quo minus non neque iure officiis!

Align top

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Consequatur sint mollitia itaque reiciendis quam unde veritatis, reprehenderit earum dolorum temporibus ut provident, placeat magni minus iusto eligendi? Odit dignissimos, quisquam.

Iste culpa aliquam nostrum aliquid vitae, doloremque delectus adipisci nemo, alias sint, quos illum possimus assumenda et ad modi est officia. Adipisci rem ut, deserunt voluptatum maiores quae eum, quasi.

Exercitationem ipsum aliquam dolorum architecto neque, autem obcaecati natus, hic perferendis earum deleniti ipsa nisi fugiat similique explicabo vitae veritatis doloribus atque mollitia, incidunt dolores nam nemo laborum! Accusamus, eligendi!

Omnis voluptates excepturi architecto dignissimos nisi accusantium praesentium nesciunt deleniti velit sapiente officiis possimus rerum exercitationem vitae aperiam amet nulla dolorem molestiae mollitia quasi a ut veritatis, quos laudantium assumenda.

Quisquam perspiciatis reprehenderit fuga! Sunt laborum aliquam libero tempora quos sit quia, amet perspiciatis, velit nam dolore doloribus, reiciendis quo fugiat totam quod qui. Quo minus non neque iure officiis!

Align middle

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Consequatur sint mollitia itaque reiciendis quam unde veritatis, reprehenderit earum dolorum temporibus ut provident, placeat magni minus iusto eligendi? Odit dignissimos, quisquam.

Iste culpa aliquam nostrum aliquid vitae, doloremque delectus adipisci nemo, alias sint, quos illum possimus assumenda et ad modi est officia. Adipisci rem ut, deserunt voluptatum maiores quae eum, quasi.

Exercitationem ipsum aliquam dolorum architecto neque, autem obcaecati natus, hic perferendis earum deleniti ipsa nisi fugiat similique explicabo vitae veritatis doloribus atque mollitia, incidunt dolores nam nemo laborum! Accusamus, eligendi!

Omnis voluptates excepturi architecto dignissimos nisi accusantium praesentium nesciunt deleniti velit sapiente officiis possimus rerum exercitationem vitae aperiam amet nulla dolorem molestiae mollitia quasi a ut veritatis, quos laudantium assumenda.

Quisquam perspiciatis reprehenderit fuga! Sunt laborum aliquam libero tempora quos sit quia, amet perspiciatis, velit nam dolore doloribus, reiciendis quo fugiat totam quod qui. Quo minus non neque iure officiis!

Align bottom

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Consequatur sint mollitia itaque reiciendis quam unde veritatis, reprehenderit earum dolorum temporibus ut provident, placeat magni minus iusto eligendi? Odit dignissimos, quisquam.

Iste culpa aliquam nostrum aliquid vitae, doloremque delectus adipisci nemo, alias sint, quos illum possimus assumenda et ad modi est officia. Adipisci rem ut, deserunt voluptatum maiores quae eum, quasi.

Exercitationem ipsum aliquam dolorum architecto neque, autem obcaecati natus, hic perferendis earum deleniti ipsa nisi fugiat similique explicabo vitae veritatis doloribus atque mollitia, incidunt dolores nam nemo laborum! Accusamus, eligendi!

Omnis voluptates excepturi architecto dignissimos nisi accusantium praesentium nesciunt deleniti velit sapiente officiis possimus rerum exercitationem vitae aperiam amet nulla dolorem molestiae mollitia quasi a ut veritatis, quos laudantium assumenda.

Quisquam perspiciatis reprehenderit fuga! Sunt laborum aliquam libero tempora quos sit quia, amet perspiciatis, velit nam dolore doloribus, reiciendis quo fugiat totam quod qui. Quo minus non neque iure officiis!

Justify

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Beatae praesentium veniam, earum sit velit vitae reiciendis quis. Veritatis, minima omnis! Esse vel nostrum facilis cum sapiente vitae, molestias mollitia dolor!

Aspernatur quam facere, consequatur, placeat ipsam tempora exercitationem quo officia repellendus cum at sint incidunt, eum impedit perferendis praesentium! Et nulla culpa soluta, magni ut pariatur porro quo reprehenderit atque!

Reprehenderit mollitia quas omnis tempore architecto accusamus natus repudiandae ex recusandae dignissimos obcaecati quos facilis, hic ipsa ipsam doloribus veniam sunt, officiis. Vel quibusdam voluptatem quos ea natus neque veritatis!

Qui hic facilis ducimus illo quibusdam rem possimus eius, odit ipsam quidem vel, voluptatibus ad autem aut, ratione modi quisquam consequuntur? Expedita a hic quidem, blanditiis ipsam sequi, necessitatibus repellat.

Inline

Lorem ipsum.

Architecto, beatae!

Est, maiores.

Odio, hic!

Quasi, commodi.

Animi, ratione.


text:
from flask.ext.script import Manager, Shell, prompt_bool
from flask.ext.migrate import MigrateCommand
from service import db, config, create_app, models
from subprocess import Popen, call

"Main python process which allows database creation/modification and executes flask server"

app = create_app(config.DevelopmentConfig)

manager = Manager(app, with_default_commands=False)
manager.add_command('db', MigrateCommand)
manager.add_command('shell', Shell())

@manager.command
def build():
    "Builds frontend dependencies"
    call('gulp default', cwd='service/frontend', shell=True)

@manager.command
def run():
    "Runs the Flask development server i.e. app.run()"
    Popen('gulp', cwd='service/frontend', shell=True)
    app.run(host='localhost', port=5000)

@MigrateCommand.command
def create():
    "Creates database tables from sqlalchemy models"
    db.create_all()

@MigrateCommand.command
def drop():
    "Drops all database tables"
    if prompt_bool("Are you sure you want to lose all your data"):
        db.drop_all()

@MigrateCommand.command
def populate():
    "Populates database tables with default entries"
    # TODO: Store info within the models rather than out here
    guest_group = models.members.Groups("guest")
    member_group = models.members.Groups("member")
    admin_group = models.members.Groups("admin")
    db.session.add(guest_group)
    db.session.add(member_group)
    db.session.add(admin_group)
    db.session.commit()

    member = models.members.Members()
    member.sid = 1
    member.email = 'dylan@allbee.org'
    member.name = 'Dylan'
    member.password = 'password'
    db.session.add(member)
    db.session.commit()

    content = models.content.Content()
    content.member_id = 1
    content.path = 'index'
    content.title = 'Default Page'
    content.description = 'Page description'
    content.data = 'Here is some page data **whaaa** <html>'
    db.session.add(content)
    db.session.commit()

if __name__ == '__main__':
    manager.run()


text:
using System;

namespace _08.TrapezoidsArea
{
    class TrapezoidArea
    {
        static void Main(string[] args)
        {
            double a = double.Parse(Console.ReadLine());;
            double b = double.Parse(Console.ReadLine());
            double h = double.Parse(Console.ReadLine());
            double area = ((a + b) / 2) * h;
            Console.WriteLine("{0:F7}", area);
         }
    }
}


text:
import React, { PropTypes } from 'react';

export default class Counter {
  static propTypes = {
    increment: PropTypes.func.isRequired,
    decrement: PropTypes.func.isRequired,
    counter: PropTypes.number.isRequired
  };

  render() {
    const { increment, incrementIfOdd, decrement, counter } = this.props;
    return (
      <p>
        Clicked: {counter} times
        {' '}
        <button onClick={increment}>+</button>
        {' '}
        <button onClick={decrement}>-</button>
        {' '}
        <button onClick={incrementIfOdd}>Increment if odd</button>
      </p>
    );
  }
}


text:
require("./lib/Application/DtoFactory");
require("./lib/Application/Dto");
require("./lib/Application/Renderer");
require("./lib/Node/Config");


text:
<?php
/**
 * Created by PhpStorm.
 * User: Louis Sicard
 * Date: 18/05/2016
 * Time: 15:31
 */

namespace CtSearchBundle\DependencyInjection;

use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;

class CtSearchCompilerPass implements CompilerPassInterface
{
  public function process(ContainerBuilder $container)
  {
    $services = $container->findTaggedServiceIds("ctsearch.datasource");
    $container->setParameter("ctsearch.datasources", array_keys($services));
    $filterServices = $container->findTaggedServiceIds("ctsearch.filter");
    $container->setParameter("ctsearch.filters", array_keys($filterServices));
    $analyticsServices = $container->findTaggedServiceIds("ctsearch.analytics");
    $container->setParameter("ctsearch.analytics", array_keys($analyticsServices));
  }

}


text:
<?php

namespace Tienvx\Bundle\MbtBundle\Message;

class CreateBugMessage implements MessageInterface
{
    public function __construct(
        protected int $taskId,
        protected array $steps,
        protected string $message
    ) {
    }

    public function getTaskId(): int
    {
        return $this->taskId;
    }

    public function getSteps(): array
    {
        return $this->steps;
    }

    public function getMessage(): string
    {
        return $this->message;
    }
}


text:
package pl.nort.dayoneevernote.dayone.convert;

import java.text.ParseException;
import java.util.UUID;

import org.springframework.stereotype.Component;

import com.dd.plist.NSArray;
import com.dd.plist.NSDate;
import com.dd.plist.NSDictionary;
import com.google.common.base.Strings;
import com.overzealous.remark.Remark;

import pl.nort.dayoneevernote.exception.ConversionException;
import pl.nort.dayoneevernote.note.Note;
import pl.nort.dayoneevernote.translate.ExternalNoteFactory;

/**
 * Builds Dayone note from a {@link pl.nort.dayoneevernote.note.Note}
 *
 * @author Norbert Potocki
 */
@Component
public class NoteFactory implements ExternalNoteFactory<NSDictionary> {

    public static final String CREATION_DATE_KEY = "Creation Date";
    public static final String BODY_KEY = "Entry Text";
    public static final String UUID_KEY = "UUID";
    public static final String STARRED_KEY = "Starred";
    public static final String TIMEZONE_KEY = "Time Zone";

    private final Remark remark = new Remark();

    @Override
    public NSDictionary fromNote(Note note) {

        String uuid = UUID.randomUUID().toString().replace("-", "").toUpperCase();

        NSDate creationDate;
        try {
            creationDate = new NSDate(note.getCreationTime().toString("yyyy-MM-dd'T'HH:mm:ss'Z'Z"));
        } catch (ParseException e) {
            throw new ConversionException(note.getCreationTime().toString(), e);
        }

        // Convert body to Remark
        String remarkBody = remark.convert(note.getBody());

        String body = (Strings.isNullOrEmpty(note.getTitle()) ? "" : note.getTitle() + "\n\n")
                + remarkBody;

        NSDictionary root = new NSDictionary();

        root.put(CREATION_DATE_KEY, creationDate);
        root.put(BODY_KEY, body);
        root.put(STARRED_KEY, false);
        root.put("Tags", new NSArray(0));
        root.put(TIMEZONE_KEY, "America/Vancouver");
        root.put(UUID_KEY, uuid);

        if(note.getLocation().isPresent()) {
            LocationBuilder.addLocation(root, new LocationBuilder()
                    .withLongitude(note.getLocation().get().getX())
                    .withLatitude(note.getLocation().get().getY())
                    .build());
        }

        return root;
    }

}


text:
These [XSLT](http://www.w3schools.com/xsl/ "XSLT") scripts allow you to export [mind maps](http://en.wikipedia.org/wiki/Mind_map "mind maps") created using [FreeMind](http://freemind.sourceforge.net "FreeMind") into [JSON](http://en.wikipedia.org/wiki/JSON "JSON") format files.

Add this to your toolbox for Web & Javascript development.
I'm using it to create menus and tree controls.

In FreeMind ...

1. Open your mind map file (MyMap.mm)
1. From the menu select:  File | Export | Using XSTL ...
1. In the popup dialog select the **Freemind2json.xsl**  file.
1. And then select your JSON output file (typically a .js or .json file type).
1. Press **Export** to export the file.

## Export a Sencha TreeStore ##

If you're creating JSON data for a [Sencha ](http://www.sencha.com) TreeStore  you can use **FreeMind2TreeStoreJSON.xsl** script.  This will save you copy/pasting 'leaf:true' ad nausium on each leaf node. You can also maintain your own attributes in FreeMind or prune the exported tree by setting attribute with leaf=true inside FreenMind  (select a node then select 'Edit Attributes' from the context menu).  Any other custom attributes you add inside FreeMind will be exported as a JSON attribute.

## Roll your own ##
You'll find these scripts a good starting point for your own custom export.
It's fairly easy to convert any other FreeMind attributes or modify the resulting JSON content or formatting.

Enjoy :)
Tony.


text:
if (FML.isModLoaded("ForgeMicroblock") && ForgeMicroblock_enabled) {

    // Special handler for cleanly removing them.
    ForgeMicroblock.obliterate_microblocks([1, 2, 4, 257, 258, 260, 513, 514, 516, 769, 770, 772], ForgeMicroblock.getRandomMaterial());
}


text:
package printer

import (
	"fmt"
	"io"
	"reflect"
	"strings"
	"text/tabwriter"
	"time"

	cloudapi "pharmer.dev/cloud/apis/cloud/v1"
	"pharmer.dev/cloud/pkg/credential"
	api "pharmer.dev/pharmer/apis/v1alpha1"

	"github.com/pkg/errors"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/klog"
	clusterapi "sigs.k8s.io/cluster-api/pkg/apis/cluster/v1alpha1"
)

// ref: k8s.io/kubectl/resource_printer.go

const (
	tabwriterMinWidth = 10
	tabwriterWidth    = 4
	tabwriterPadding  = 3
	tabwriterPadChar  = ' '
	tabwriterFlags    = 0
)

type handlerEntry struct {
	printFunc reflect.Value
}

type PrintOptions struct {
	Wide bool
}

type HumanReadablePrinter struct {
	handlerMap        map[reflect.Type]*handlerEntry
	options           PrintOptions
	lastType          reflect.Type
	enablePrintHeader bool
}

func NewHumanReadablePrinter(options PrintOptions) *HumanReadablePrinter {
	printer := &HumanReadablePrinter{
		handlerMap:        make(map[reflect.Type]*handlerEntry),
		options:           options,
		enablePrintHeader: true,
	}
	printer.addDefaultHandlers()
	return printer
}

func ShortHumanDuration(d time.Duration) string {
	if seconds := int(d.Seconds()); seconds <= 0 {
		return fmt.Sprintf("0s")
	} else if seconds < 60 {
		return fmt.Sprintf("%ds", seconds)
	} else if minutes := int(d.Minutes()); minutes < 60 {
		return fmt.Sprintf("%dm", minutes)
	} else if hours := int(d.Hours()); hours < 24 {
		return fmt.Sprintf("%dh", hours)
	} else if hours < 24*364 {
		return fmt.Sprintf("%dd", hours/24)
	}
	return fmt.Sprintf("%dy", int(d.Hours()/24/365))
}

func (h *HumanReadablePrinter) addDefaultHandlers() {
	_ = h.Handler(h.printCluster)
	_ = h.Handler(h.printCredential)
	_ = h.Handler(h.printMachineSet)
}

func (h *HumanReadablePrinter) PrintHeader(enable bool) {
	h.enablePrintHeader = enable
}

func (h *HumanReadablePrinter) Handler(printFunc interface{}) error {
	printFuncValue := reflect.ValueOf(printFunc)
	if err := h.validatePrintHandlerFunc(printFuncValue); err != nil {
		klog.Errorf("Unable to add print handler: %v", err)
		return err
	}

	objType := printFuncValue.Type().In(0)

	h.handlerMap[objType] = &handlerEntry{
		printFunc: printFuncValue,
	}
	return nil
}

func (h *HumanReadablePrinter) validatePrintHandlerFunc(printFunc reflect.Value) error {
	if printFunc.Kind() != reflect.Func {
		return errors.Errorf("invalid print handler. %#v is not a function", printFunc)
	}
	funcType := printFunc.Type()
	if funcType.NumIn() != 3 || funcType.NumOut() != 1 {
		return errors.Errorf("invalid print handler." +
			"Must accept 3 parameters and return 1 value.")
	}
	if funcType.In(1) != reflect.TypeOf((*io.Writer)(nil)).Elem() ||
		funcType.In(2) != reflect.TypeOf((*PrintOptions)(nil)).Elem() ||
		funcType.Out(0) != reflect.TypeOf((*error)(nil)).Elem() {
		return errors.Errorf("invalid print handler. The expected signature is: "+
			"func handler(obj %v, w io.Writer, options PrintOptions) error", funcType.In(0))
	}
	return nil
}

func getColumns(t reflect.Type) []string {
	columns := make([]string, 0)
	columns = append(columns, "NAME")
	switch t.String() {
	case "*v1alpha1.Cluster":
		columns = append(columns, "PROVIDER")
		columns = append(columns, "ZONE")
		columns = append(columns, "VERSION")
		columns = append(columns, "RUNNING SINCE")
		columns = append(columns, "STATUS")
	case "*v1alpha1.NodeGroup":
		columns = append(columns, "Cluster")
		columns = append(columns, "Node")
		columns = append(columns, "SKU")
	case "*v1alpha1.Credential":
		columns = append(columns, "Provider")
		columns = append(columns, "Data")
	case "*cluster.k8s.io/v1alpha1":
		columns = append(columns, "Cluster")
		columns = append(columns, "Node")
		columns = append(columns, "SKU")
	}
	return columns
}

func (h *HumanReadablePrinter) printCluster(item *api.Cluster, w io.Writer, options PrintOptions) (err error) {
	name := item.Name

	if _, err = fmt.Fprintf(w, "%s\t", name); err != nil {
		return
	}

	if _, err = fmt.Fprintf(w, "%s\t", item.Spec.Config.Cloud.CloudProvider); err != nil {
		return
	}
	if _, err = fmt.Fprintf(w, "%s\t", item.Spec.Config.Cloud.Zone); err != nil {
		return
	}
	if _, err = fmt.Fprintf(w, "%s\t", item.Spec.Config.KubernetesVersion); err != nil {
		return
	}
	if _, err = fmt.Fprintf(w, "%s\t", TranslateTimestamp(item.CreationTimestamp)); err != nil {
		return
	}
	if _, err = fmt.Fprintf(w, "%s\t", item.Status.Phase); err != nil {
		return
	}
	return PrintNewline(w)
}

func (h *HumanReadablePrinter) printMachineSet(item *clusterapi.MachineSet, w io.Writer, options PrintOptions) error {
	name := item.Name

	if _, err := fmt.Fprintf(w, "%s\t", name); err != nil {
		return err
	}

	if _, err := fmt.Fprintf(w, "%s\t", item.ClusterName); err != nil {
		return err
	}

	if _, err := fmt.Fprintf(w, "%v\t", item.Spec.Template.Name); err != nil {
		return err
	}
	if _, err := fmt.Fprintf(w, "%s\t", item.Spec.Template.Spec.Namespace); err != nil {
		return err
	}
	return PrintNewline(w)
}

func (h *HumanReadablePrinter) printCredential(item *cloudapi.Credential, w io.Writer, options PrintOptions) error {
	name := item.Name

	if _, err := fmt.Fprintf(w, "%s\t", name); err != nil {
		return err
	}

	if _, err := fmt.Fprintf(w, "%s\t", item.Spec.Provider); err != nil {
		return err
	}
	if _, err := fmt.Fprintf(w, "%s\t", credential.CommonSpec(item.Spec).String()); err != nil {
		return err
	}
	return PrintNewline(w)
}

func (h *HumanReadablePrinter) PrintObj(obj runtime.Object, output io.Writer) error {
	w, found := output.(*tabwriter.Writer)
	if !found {
		w = GetNewTabWriter(output)
		defer w.Flush()
	}

	t := reflect.TypeOf(obj)
	if handler := h.handlerMap[t]; handler != nil {

		if t != h.lastType || h.enablePrintHeader {
			headers := getColumns(t)
			if h.lastType != nil {
				if err := PrintNewline(w); err != nil {
					return err
				}
			}
			if err := h.printHeader(headers, w); err != nil {
				return err
			}
			h.lastType = t
			h.enablePrintHeader = false
		}
		args := []reflect.Value{reflect.ValueOf(obj), reflect.ValueOf(w), reflect.ValueOf(h.options)}
		resultValue := handler.printFunc.Call(args)[0]
		if resultValue.IsNil() {
			return nil
		}
		return resultValue.Interface().(error)
	}

	return errors.Errorf(`pharmer doesn't support: "%v"`, t)
}

func (h *HumanReadablePrinter) HandledResources() []string {
	return []string{}
}

func (h *HumanReadablePrinter) AfterPrint(io.Writer, string) error {
	return nil
}

func (h *HumanReadablePrinter) IsGeneric() bool {
	return false
}

func (h *HumanReadablePrinter) printHeader(columnNames []string, w io.Writer) error {
	if _, err := fmt.Fprintf(w, "%s\n", strings.Join(columnNames, "\t")); err != nil {
		return err
	}
	return nil
}

func PrintNewline(w io.Writer) error {
	if _, err := fmt.Fprintf(w, "\n"); err != nil {
		return err
	}
	return nil
}

func TranslateTimestamp(timestamp metav1.Time) string {
	if timestamp.IsZero() {
		return "<unknown>"
	}
	return ShortHumanDuration(time.Since(timestamp.Time))
}

func GetNewTabWriter(output io.Writer) *tabwriter.Writer {
	return tabwriter.NewWriter(
		output,
		tabwriterMinWidth,
		tabwriterWidth,
		tabwriterPadding,
		tabwriterPadChar,
		tabwriterFlags,
	)
}


text:
/**
 *
 */
package com.browseengine.bobo.facets.impl;

import java.util.NoSuchElementException;

import com.browseengine.bobo.api.LongFacetIterator;
import com.browseengine.bobo.facets.data.TermLongList;
import com.browseengine.bobo.util.BigSegmentedArray;

public class DefaultLongFacetIterator extends LongFacetIterator {

  public TermLongList _valList;
  private final BigSegmentedArray _count;
  private final int _countlength;
  private final int _countLengthMinusOne;
  private int _index;

  public DefaultLongFacetIterator(TermLongList valList, BigSegmentedArray countarray,
      int countlength, boolean zeroBased) {
    _valList = valList;
    _countlength = countlength;
    _count = countarray;
    _countLengthMinusOne = _countlength - 1;
    _index = -1;
    if (!zeroBased) _index++;
    facet = TermLongList.VALUE_MISSING;
    count = 0;
  }

  /*
   * (non-Javadoc)
   * @see com.browseengine.bobo.api.FacetIterator#getFacet()
   */
  public String getFacet() {
    if (facet == TermLongList.VALUE_MISSING) return null;
    return _valList.format(facet);
  }

  @Override
  public String format(long val) {
    return _valList.format(val);
  }

  @Override
  public String format(Object val) {
    return _valList.format(val);
  }

  /*
   * (non-Javadoc)
   * @see com.browseengine.bobo.api.FacetIterator#getFacetCount()
   */
  public int getFacetCount() {
    return count;
  }

  /*
   * (non-Javadoc)
   * @see java.util.Iterator#hasNext()
   */
  @Override
  public boolean hasNext() {
    return (_index < _countLengthMinusOne);
  }

  /*
   * (non-Javadoc)
   * @see java.util.Iterator#next()
   */
  @Override
  public String next() {
    if ((_index >= 0) && (_index >= _countLengthMinusOne)) throw new NoSuchElementException(
        "No more facets in this iteration");
    _index++;
    facet = _valList.getPrimitiveValue(_index);
    count = _count.get(_index);
    return _valList.get(_index);
  }

  /*
   * (non-Javadoc)
   * @see com.browseengine.bobo.api.LongFacetIterator#nextLong()
   */
  @Override
  public long nextLong() {
    if (_index >= _countLengthMinusOne) throw new NoSuchElementException(
        "No more facets in this iteration");
    _index++;
    facet = _valList.getPrimitiveValue(_index);
    count = _count.get(_index);
    return facet;
  }

  /*
   * (non-Javadoc)
   * @see java.util.Iterator#remove()
   */
  @Override
  public void remove() {
    throw new UnsupportedOperationException("remove() method not supported for Facet Iterators");
  }

  /*
   * (non-Javadoc)
   * @see com.browseengine.bobo.api.FacetIterator#next(int)
   */
  @Override
  public String next(int minHits) {
    while (++_index < _countlength) {
      if (_count.get(_index) >= minHits) {
        facet = _valList.getPrimitiveValue(_index);
        count = _count.get(_index);
        return _valList.format(facet);
      }
    }
    facet = TermLongList.VALUE_MISSING;
    count = 0;
    return null;
  }

  /*
   * (non-Javadoc)
   * @see com.browseengine.bobo.api.LongFacetIterator#nextLong(int)
   */
  @Override
  public long nextLong(int minHits) {
    while (++_index < _countlength) {
      if (_count.get(_index) >= minHits) {
        facet = _valList.getPrimitiveValue(_index);
        count = _count.get(_index);
        return facet;
      }
    }
    facet = TermLongList.VALUE_MISSING;
    count = 0;
    return facet;
  }
}


text:
package com.linstid.energydashws.entities;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

import com.google.code.morphia.annotations.Entity;
import com.google.code.morphia.annotations.Id;
import com.google.code.morphia.annotations.Property;

@Entity(value = "hours_in_day", noClassnameStored = true)
public class HoursInDayEntity implements Serializable {

	@Id
	private int id;

	@Property("count")
	private int count;

	@Property("average_usage")
	private float averageUsage;

	@Property("average_tempf")
	private float averageTempF;

	@Property("timestamps")
	private List<Date> timestamps;

	public int getCount() {
		return count;
	}

	public void setCount(int count) {
		this.count = count;
	}

	public float getAverageUsage() {
		return averageUsage;
	}

	public void setAverageUsage(float averageUsage) {
		this.averageUsage = averageUsage;
	}

	public float getAverageTempF() {
		return averageTempF;
	}

	public void setAverageTempF(float averageTempF) {
		this.averageTempF = averageTempF;
	}

	public List<Date> getTimestamps() {
		return timestamps;
	}

	public void setTimestamps(List<Date> timestamps) {
		this.timestamps = timestamps;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}
}


text:
Implement a web application, which makes organizing learning resources easy:

* Have a login / register functionality. You can use OAuth, if you want (and can)
* Once logged in, have an interface in which you should be able to create a **Learning Track**

## Learning Tracks and Groups

One learning track should have:

* A name
* A description
* A list of online resources, organizded in different groups of the learning track.

One resource can be just a URL to somewhere else. Nothing more.

The user should be able to organize a learning track by creating new groups and adding resources to a given group.

Once created, the learning track should be able to:

* Be shared with a unique URL to everyone, withour requiring a login to see it.
* Be edited by the user that created it.

## Example

In a markdown, here is how one learning track should look like:

```markdown
# Track for JavaScript

Description - some resources to learn JavaScript

## Group 1 - Getting your way arround

* https://www.javascript.com/
* https://www.codeschool.com/paths/javascript

## Group 2 - HackBulgaria's JS Courses

* https://github.com/HackBulgaria/Frontend-JavaScript-1
* https://github.com/HackBulgaria/Frontend-JavaScript-2

## Group 3 - Backend JavaScript

* https://nodejs.org/
* https://github.com/HackBulgaria/NodeJS-1
```

Once created, the track should be able to be shared with a link. For example:

```
http://example/tracks/11ffhhj234
```


text:
The `MMM-TwitterTrendsByPlace` module is a module design to display the trending topics from Twitter based on a given locale. The trends are automatically sorted by the volume of tweets for that trending topic and then displayed in that order, optionally along with their rank and their tweet volume shown.

Example:

![Full](images/example.jpg)

## Dependencies / Requirements

This module requires the use of the `twitter` package for node.js. To install this please run `npm install twitter` from the root directory of your Magic Mirror installation.

This module also requires Twitter access tokens and keys. For more information on acquiring these please visit <https://dev.twitter.com/oauth/overview/application-owner-access-tokens>.

You will need to set a WOEID value for the place (likely a city) to gather the trending topics for. WOEID values, aka "Where On Earth ID" values, are maintained by Yahoo! and can be searched for at <http://woeid.rosselliot.co.nz/lookup/>.

NOTE: That while WOEID's exist for nearly every city or place on Earth, trending topics are only available for the very largest cities or places. If you discover an error when running this module change the WOEID to an appropriate very large city and try again.

To see a short, but not at all comprehensive, list of cities and their WOEID's please check the [woeid_short_list.md](woeid_short_list.md) file included in this repository.

## Using the module

To use this module, add it to the modules array in the `config/config.js` file:
````javascript
modules: [
	{
		module: 'MMM-TwitterTrendsByPlace',
		position: 'bottom_left',
		config: {
		// visit the url below for the twitter keys/tokens
		// https://dev.twitter.com/oauth/overview/application-owner-access-tokens
			consumer_key: 'FILL IN',
			consumer_secret: 'FILL IN',
			access_token_key: 'FILL IN',
			access_token_secret: 'FILL IN',
		// set the display name/title for the place
			placeName: 'New York, NY',
		// set the woeid for the place, see documentation for more
		// http://woeid.rosselliot.co.nz/lookup/
			placeWoeid: '2459115',
		}
	}
]
````

## Configuration options

The following properties can be configured:

			Option
			Description

			consumer_key
			Used by the Twitter package in order to collect the trends. For more visit https://dev.twitter.com/oauth/overview/application-owner-access-tokens.

This value is REQUIRED

			consumer_secret
			Used by the Twitter package in order to collect the trends. For more visit https://dev.twitter.com/oauth/overview/application-owner-access-tokens.

This value is REQUIRED

			access_token_key
			Used by the Twitter package in order to collect the trends. For more visit https://dev.twitter.com/oauth/overview/application-owner-access-tokens.

This value is REQUIRED

			access_token_secret
			Used by the Twitter package in order to collect the trends. For more visit https://dev.twitter.com/oauth/overview/application-owner-access-tokens.

This value is REQUIRED

			placeName
			The name/title of the location for which the Twitter trending topics will be gathered for. This should match the place set by the placeWoeid value. However, it can be set to any string and allows the user to decide based on their display preference, i.e. could be "New York", "NYC", "New York, New York", "The Big Apple", etc.

Example: New York, NY

This value is REQUIRED

			placeWoeid
			The "Where On Earth ID"/WOEID value for the city or place you are trying to gather trending topics for. These can be searched for at http://woeid.rosselliot.co.nz/lookup/. NOTE: Trending Topics are only available for the largest cities or places, if the WOEID you use does not work pick another large city or place and try again.

Example: 2459115

This value is REQUIRED

			numberOfTrendsToShow
			The number of trending topics to list. If set to 0 it will show all the trending topics for the place that have any tweet volume information available. Do note that the number of trending topics provided by Twitter is not fixed and can be many or just a few.

Example: 6

Default value: 10

This value is OPTIONAL

			showTweetVolume
			Enable this to show the tweet volume for a particular trending topic, i.e. "1.31m", "378k", "13k", etc.

Example: false

Default value: true

This value is OPTIONAL

			showTrendRank
			Enable this to show the rank of the trend, effectively the order after being sorted by the tweet volume, i.e. "1", "2", "3", etc.

Example: false

Default value: true

This value is OPTIONAL

			refreshRate
			Specified in MINUTES, set the speed at which the trending topics are updated. Note that if a value less than 15 is specified it will be set to 15; this is to prevent any possible over-polling of Twitter. Also, the trending topics are no updated nearly as often as a typical Twitter home timeline is.

Example: 45

Default value: 20

This value is OPTIONAL

			fade
			Enables the fade effect as seen visibly moving down the trending topics. This is the identical effect as seen in the weather forecast default module.

Example: true

Default value: false

This value is OPTIONAL

			fadePoint
			The decimal percentage of where in the list of trending topics to begin the fade effect. This is identical to the effect seen in the weather forecast default module.

Example: 0.25

Default value: 0.5

This value is OPTIONAL


text:
module Maestrano::Connector::Rails
  class UserOrganizationRel < ActiveRecord::Base
    #===================================
    # Associations
    #===================================
    belongs_to :user
    belongs_to :organization
  end
end


text:
<?php
require('{{ CONFIG_FILE }}');

if (empty($CONFIG)){
  throw new Exception('Config is empty');
}

$cnt = count($argv);
$trusted = array('localhost');
for($i=1; $i<$cnt; $i++){
  $trusted[] = trim($argv[$i]);
}

$CONFIG['trusted_domains'] = $trusted;
var_export($CONFIG);


text:
require 'job_crawler/version'

# Some comment
module JobCrawler
  def test
    'test'
  end
end


text:
'''
Data processed
     Data Page 16
          Instantaneous speed 0.001 m/s
     Data Page 22
          Instantaneous Cadence spm
          Instantaneous power watts
'''

import time
import os
import fcntl
import sys, hashlib

from ant.core import driver
from ant.core.node import Node, Network, ChannelID
from ant.core.constants import NETWORK_KEY_ANT_PLUS, NETWORK_NUMBER_PUBLIC
from ant.plus.rower import *
from ant.plus.bikeTrainer import *
from ant.core.resetUSB import reset_USB_Device
from config import *

from ant.plus.PowerMeterTx import PowerMeterTx
from ant.plus.SpeedTx import SpeedTx

########################   Get the serial number of Raspberry Pi

def getserial():
    # Extract serial from cpuinfo file
    cpuserial = "0000000000000000"
    try:
        f = open('/proc/cpuinfo', 'r')
        for line in f:
            if line[0:6] == 'Serial':
                cpuserial = line[10:26]
        f.close()
    except:
        cpuserial = "ERROR000000000"
    return cpuserial

####################################################################

C2 = False
myWheel = 2200000

#
# ok I own a C2 rover but it's now 450 km away, I'm at winter residence
# btw I got to level 50 on Zwift with that python assembly
#

if (C2):
    POWER_ADJUST = 1.25
    SPEED_ADJUST = 2.5
    RPM_ADJUST = 3.0
else:
    print("C2 Rower simulated via Simulant bike trainer for debug")
    POWER_ADJUST = 1.0
    SPEED_ADJUST = 1.0
    RPM_ADJUST = 1.0

POWER_SENSOR_ID = int(int(hashlib.md5(getserial().encode()).hexdigest(), 16) & 0xfffe) + 1
SPEED_SENSOR_ID = int(int(hashlib.md5(getserial().encode()).hexdigest(), 16) & 0xfffe) + 2

#-------------------------------------------------#
#  ANT Callbacks                                  #
#-------------------------------------------------#
def device_paired(device_profile, channel_id):
    print(f'Connected to {device_profile.name} ({channel_id.deviceNumber})')

def search_timed_out(device_profile):
    print(f'Could not connect to {device_profile.name}')

def channel_closed(device_profile):
    print(f'Channel closed for {device_profile.name}')

def Rower(elapsedTime, distanceTraveled, msSecSpeed, kmhSpeed, cadence, power):
    print("INPUT --- Speed Km/h {} Cadence {} Power {}".format(str(kmhSpeed), str(cadence), str(power)))
    speed_meter.update(myWheel, (1+(msSecSpeed*SPEED_ADJUST)))
    power_meter.update(int(power*POWER_ADJUST), int(cadence*RPM_ADJUST))

#-------------------------------------------------#
#  Initialization                                 #
#-------------------------------------------------#

try:
    reset_USB_Device()
except Exception as ex:
   print(ex)

antnode = Node(driver.USB2Driver(log=LOG, debug=DEBUG, idProduct=0x1008))
try:
    antnode.start()
    network = Network(key=NETWORK_KEY_ANT_PLUS, name='N:ANT+')
    antnode.setNetworkKey(NETWORK_NUMBER_PUBLIC, network)

    speed_meter = SpeedTx(antnode, SPEED_SENSOR_ID)
    speed_meter.open()
    print("SUCCESFULLY STARTED speed meter with ANT+ ID " + repr(SPEED_SENSOR_ID))
    power_meter = PowerMeterTx(antnode, POWER_SENSOR_ID)
    power_meter.open()
    print("SUCCESFULLY STARTED power meter with ANT+ ID " + repr(POWER_SENSOR_ID))

    if (C2):
        myTrainer = rower(antnode, network,
             {'onDevicePaired' : device_paired,
              'onSearchTimeout': search_timed_out,
              'onChannelClosed': channel_closed,
              'onRower'  : Rower})
    else:
        myTrainer = bikeTrainer(antnode, network,
             {'onDevicePaired' : device_paired,
              'onSearchTimeout': search_timed_out,
              'onChannelClosed': channel_closed,
              'onBikeTrainer'  : Rower})

    # Unpaired, search:
    myTrainer.open()
    print('ANT started. Connecting to devices...')
except ANTException as err:
    print(f'Could not start ANT.\n{err}')

#######################################################################################

while True:
    try:
        time.sleep(1)
    except KeyboardInterrupt:
        break

myTrainer.close()
antnode.stop()