text:
/*
 * 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.
 */
package org.apache.bookkeeper.api.kv.result;

import java.util.List;

/**
 * Delete result.
 */
public interface DeleteResult<K, V> extends Result<K, V> {

    /**
     * Returns the number of kv pairs deleted.
     *
     * @return the number of kv pairs deleted.
     */
    long numDeleted();

    /**
     * Returns the list of previous kv pairs of the keys
     * deleted in ths op.
     *
     * @return the list of previous kv pairs.
     */
    List<KeyValue<K, V>> prevKvs();

    /**
     * Get the list of previous kv pairs and clear them from the result.
     *
     * @return the list of previous kv pairs.
     */
    List<KeyValue<K, V>> getPrevKvsAndClear();

}

redpajama_set_name: RedPajamaGithub


text:
namespace MvcTemplate.Web.Controllers
{
    public enum ManageMessageId
    {
        AddPhoneSuccess = 0,
        ChangePasswordSuccess = 1,
        SetTwoFactorSuccess = 2,
        SetPasswordSuccess = 3,
        RemoveLoginSuccess = 4,
        RemovePhoneSuccess = 5,
        Error = 6
    }
}


text:
class ListNode(object):
    def __init__(self, x):
        self.val = x
        self.next = None

class Solution(object):
    def getDecimalValue(self, head):
        """
        :type head: ListNode
        :rtype: int
        """
        result = 0
        p = head

        while p:
            result *= 2
            result += p.val
            p = p.next

        return result


text:
layout: page
title: Palace Motors Executive Retreat
date: 2016-05-24
author: Justin Mclaughlin
tags: weekly links, java
status: published
summary: Duis consectetur nec ante vel interdum.
banner: images/banner/leisure-02.jpg
booking:
  startDate: 06/24/2017
  endDate: 06/26/2017
  ctyhocn: MEMSGHX
  groupCode: PMER
published: true
---
Donec nulla lacus, accumsan elementum fermentum sit amet, viverra vel est. Donec laoreet lacus id vulputate laoreet. Quisque vestibulum leo diam, sed vulputate purus aliquam et. Nulla ut tortor in erat cursus mattis luctus a diam. Phasellus quis orci eu urna vulputate sagittis. Suspendisse feugiat tempus est convallis porttitor. Mauris eu leo hendrerit, mollis augue sed, tincidunt felis. Suspendisse congue dignissim mi, elementum efficitur nisi fringilla at. In pellentesque, tortor sit amet mattis rutrum, diam ex aliquam diam, in aliquet est nisl et ipsum. Vivamus est nisl, tincidunt at suscipit a, congue a tellus. Proin sit amet consectetur dui. Sed et ligula viverra, pharetra ante et, sollicitudin risus.

* Donec facilisis felis vel risus faucibus aliquet
* Nullam vel magna maximus, mattis dui id, elementum leo
* Nullam et purus facilisis, vestibulum justo ac, ultricies mauris
* Pellentesque ornare sem et diam egestas tristique
* Phasellus faucibus risus vitae pretium vulputate.

Integer eu porta mauris, in pretium nibh. Sed interdum id tortor eget egestas. Morbi leo lorem, ullamcorper nec porta eu, consequat eu felis. Nulla ut auctor metus, at ornare mi. Suspendisse posuere molestie ligula, sit amet vehicula mi consequat a. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Suspendisse a lorem id ipsum lacinia sodales ut eu augue.


text:
#ifndef SPINSLIDER_H
#define SPINSLIDER_H

#include <QSlider>
#include <QLabel>
#include <QBoxLayout>
#include <QSpinBox>
#include <QToolButton>

namespace QSint
{

/**
    \brief Spin editor with additional buttons and slider for quick value edition.
    \since 0.2.2

    \image html SpinSlider.png An example of SpinSlider
*/
class SpinSlider : public QWidget
{
    Q_OBJECT

    Q_PROPERTY(int minimum READ minimum WRITE setMinimum)
    Q_PROPERTY(int maximum READ maximum WRITE setMaximum)
    Q_PROPERTY(int value READ value WRITE setValue)
    Q_PROPERTY(int sliderMultiplier READ sliderMultiplier WRITE setSliderMultiplier)
    Q_PROPERTY(bool showTicks READ ticksEnabled WRITE enableTicks)
    Q_PROPERTY(QString unitText READ unitText WRITE setUnitText)

public:
    /** Constructor.
      */
    explicit SpinSlider(QWidget *parent = 0);

    int value() const           { return m_editor->value(); }
    int minimum() const         { return m_editor->minimum(); }
    int maximum() const         { return m_editor->maximum(); }

    void setValue(int val)      { m_editor->setValue(val); }
    void setMinimum(int val);
    void setMaximum(int val);

    int sliderMultiplier() const         { return m_sliderMultiplier; }
    void setSliderMultiplier(int val);

    bool ticksEnabled() const                  { return m_slider->tickPosition() != QSlider::NoTicks; }
    void enableTicks(bool on = true);

    void expandVertically(bool on = true);

    void setEditorWidth(int width);
    void setUnitLabelWidth(int width);

    QString unitText() const                { return m_unitLabel->text(); }
    void setUnitText(const QString& val);

Q_SIGNALS:
    /** Signal emitted when the current index is changed either by the user or programmatically.
     */
    void valueChanged(int index);

protected Q_SLOTS:
    void OnEditorValueChanged(int val);
    void OnSliderMoved(int val);
    void OnMinButtonClicked();
    void OnMaxButtonClicked();

protected:
    void UpdateConstrains();

    QSpinBox *m_editor;
    QSlider *m_slider;
    QToolButton *m_minButton, *m_maxButton;
    QLabel *m_unitLabel;

    int m_sliderMultiplier;
};

} // namespace

#endif // SPINSLIDER_H


text:
from __future__ import unicode_literals

from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    dependencies = [
        ('clients', '0002_auto_20160628_2344'),
    ]

    operations = [
        migrations.AlterField(
            model_name='client',
            name='image',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='client', to='photologue.Photo'),
        ),
    ]


text:
<!DOCTYPE html>

    <title>Backbone Demo: Todos</title>
    <link href="todos.css" media="all" rel="stylesheet" type="text/css"/>

Todos

          <input id="new-todo" placeholder="What needs to be done?" type="text" />
          Press Enter to save this task


text:
using System;
using System.Collections.Generic;

namespace DotMaysWind.Data.Command.Function
{
    /// <summary>
    /// Sql函数类
    /// </summary>
    public class SqlFunctions
    {
        #region 字段
        private AbstractDatabase _baseDatabase;
        #endregion

        #region 构造方法
        /// <summary>
        /// 初始化新的Sql函数类
        /// </summary>
        /// <param name="baseDatabase">源数据库</param>
        public SqlFunctions(AbstractDatabase baseDatabase)
        {
            this._baseDatabase = baseDatabase;
        }
        #endregion

        #region 方法
        /// <summary>
        /// 获取Sql判空函数
        /// </summary>
        /// <param name="condition">函数条件</param>
        /// <param name="contentTwo">内容2</param>
        /// <returns>Sql判空函数</returns>
        public SqlInnerFunction IsNull(String condition, String contentTwo)
        {
            return new SqlInnerFunction(this._baseDatabase, SqlInnerFunctionType.IsNull, condition, contentTwo);
        }

        /// <summary>
        /// 获取Sql大写函数
        /// </summary>
        /// <param name="parameter">函数参数</param>
        /// <returns>Sql大写函数</returns>
        public SqlInnerFunction Upper(String parameter)
        {
            return new SqlInnerFunction(this._baseDatabase, SqlInnerFunctionType.Upper, parameter);
        }

        /// <summary>
        /// 获取Sql小写函数
        /// </summary>
        /// <param name="parameter">函数参数</param>
        /// <returns>Sql小写函数</returns>
        public SqlInnerFunction Lower(String parameter)
        {
            return new SqlInnerFunction(this._baseDatabase, SqlInnerFunctionType.Lower, parameter);
        }

        /// <summary>
        /// 获取Sql去除左边空格函数
        /// </summary>
        /// <param name="parameter">函数参数</param>
        /// <returns>Sql去除左边空格函数</returns>
        public SqlInnerFunction LTrim(String parameter)
        {
            return new SqlInnerFunction(this._baseDatabase, SqlInnerFunctionType.LTrim, parameter);
        }

        /// <summary>
        /// 获取Sql去除右边空格函数
        /// </summary>
        /// <param name="parameter">函数参数</param>
        /// <returns>Sql去除右边空格函数</returns>
        public SqlInnerFunction RTrim(String parameter)
        {
            return new SqlInnerFunction(this._baseDatabase, SqlInnerFunctionType.RTrim, parameter);
        }

        /// <summary>
        /// 获取Sql去除两边空格函数
        /// </summary>
        /// <param name="parameter">函数参数</param>
        /// <returns>Sql去除两边空格函数</returns>
        public SqlInnerFunction Trim(String parameter)
        {
            return new SqlInnerFunction(this._baseDatabase, SqlInnerFunctionType.Trim, parameter);
        }

        /// <summary>
        /// 获取Sql字符串长度函数
        /// </summary>
        /// <param name="parameter">函数参数</param>
        /// <returns>Sql字符串长度函数</returns>
        public SqlInnerFunction Length(String parameter)
        {
            return new SqlInnerFunction(this._baseDatabase, SqlInnerFunctionType.Length, parameter);
        }

        /// <summary>
        /// 获取Sql字符串提取函数
        /// </summary>
        /// <param name="parameter">函数参数</param>
        /// <param name="start">子串起始位置</param>
        /// <param name="length">子串长度</param>
        /// <returns>Sql字符串提取函数</returns>
        public SqlInnerFunction Mid(String parameter, Int32 start, Int32 length)
        {
            return new SqlInnerFunction(this._baseDatabase, SqlInnerFunctionType.Mid, parameter, start.ToString(), length.ToString());
        }

        /// <summary>
        /// 获取Sql取整函数
        /// </summary>
        /// <param name="parameter">函数参数</param>
        /// <param name="decimals">小数位数</param>
        /// <returns>Sql取整函数</returns>
        public SqlInnerFunction Round(String parameter, Int32 decimals)
        {
            return new SqlInnerFunction(this._baseDatabase, SqlInnerFunctionType.Round, parameter, decimals.ToString());
        }

        /// <summary>
        /// 获取Sql当前日期函数
        /// </summary>
        /// <returns>Sql当前日期函数</returns>
        public SqlInnerFunction Now()
        {
            return new SqlInnerFunction(this._baseDatabase, SqlInnerFunctionType.Now);
        }

        /// <summary>
        /// 获取Sql部分日期函数
        /// </summary>
        /// <param name="parameter">函数参数</param>
        /// <param name="datepartType">获取部分的类型</param>
        /// <returns>Sql部分日期函数</returns>
        public SqlInnerFunction DatePart(String parameter, SqlDatePartType datepartType)
        {
            return new SqlInnerFunction(this._baseDatabase, SqlInnerFunctionType.DatePart, parameter, ((Byte)datepartType).ToString());
        }
        #endregion
    }
}


text:
package com.dulion.astatium.service.web;

import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;

import com.dulion.astatium.service.AstatiumService;

public class ServletInitializer extends SpringBootServletInitializer {
	@Override
	protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
		return builder.sources(AstatiumService.class);
	}
}


text:
#include <string>

#include "ManagedAuthInitialize.hpp"
#include "../IAuthInitialize.hpp"
#include "../ExceptionTypes.hpp"
#include "../Properties.hpp"

using namespace System;
using namespace System::Text;
using namespace System::Reflection;

namespace apache
{
  namespace geode
  {
    namespace client
    {
      using namespace msclr::interop;

      std::shared_ptr<Properties> ManagedAuthInitializeGeneric::getCredentials(const std::shared_ptr<Properties>&
                                                                 securityprops, const std::string& server)
      {
        try {
          auto mprops = Apache::Geode::Client::Properties<String^, String^>::Create(securityprops);

          return m_getCredentials->Invoke(mprops, marshal_as<String^>(server))->GetNative();
        }
        catch (Apache::Geode::Client::GeodeException^ ex) {
          ex->ThrowNative();
        }
        catch (System::Exception^ ex) {
          Apache::Geode::Client::GeodeException::ThrowNative(ex);
        }
        return nullptr;
      }

      void ManagedAuthInitializeGeneric::close()
      {
        try {
          m_close->Invoke();
        }
        catch (Apache::Geode::Client::GeodeException^ ex) {
          ex->ThrowNative();
        }
        catch (System::Exception^ ex) {
          Apache::Geode::Client::GeodeException::ThrowNative(ex);
        }
      }

    }  // namespace client
  }  // namespace geode
}  // namespace apache


text:
package com.devng.spark.dto;

import com.owlike.genson.*;
import com.owlike.genson.stream.JsonStreamException;
import com.owlike.genson.stream.ObjectReader;
import com.owlike.genson.stream.ObjectWriter;
import spark.ResponseTransformer;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;

public class JsonUtil {

	private static final Genson genson = new GensonBuilder()
			.useIndentation(true)
			.withConverter(new LocalDateConverter(), LocalDate.class)
			.create();

	public static String toJson(Object object) {
		return genson.serialize(object);
	}

	public static <T> T fromJson(String jsonString, Class<T> type) {
		try {
			T e = genson.deserialize(jsonString, type);
			return e;
		} catch (JsonStreamException | JsonBindingException ex) {
			throw new IllegalArgumentException("Could not parse JSON: " + jsonString + ". Reason: " + ex.getMessage());
		}
	}

	public static ResponseTransformer json() {
		return JsonUtil::toJson;
	}

	private static class LocalDateConverter implements Converter<LocalDate> {

		@Override
		public void serialize(LocalDate localDate, ObjectWriter objectWriter, Context context) throws Exception {
			if (localDate == null) {
				return;
			}
			objectWriter.writeString(localDate.format(DateTimeFormatter.ISO_LOCAL_DATE));
		}

		@Override
		public LocalDate deserialize(ObjectReader objectReader, Context context) throws Exception {

			final String dateString = objectReader.valueAsString();
			if (dateString == null || dateString.isEmpty()) {
				return null;
			}
			try {
				return LocalDate.parse(dateString, DateTimeFormatter.ISO_LOCAL_DATE);
			} catch (DateTimeParseException ex) {
				throw new IllegalArgumentException(ex);
			}

		}
	}

}


text:
describe("Test this", function () {

    beforeEach(function () {
        angular.mock.module("demo-bestprice-component");
    });

    describe("Test Some", function () {

        it("test in", function(){
            expect(true).toBe(true);
            debugger;
        });

        it("test initial data", angular.mock.inject(function (dabBestpriceDataSource){
            expect(dabBestpriceDataSource).toBeDefined();
            expect(dabBestpriceDataSource.fetchDemoData()).toEqual([{
                isin: 'DE_1',
                buy: 2,
                sell: 5,
                changeAbsolute: 1,
                changeRelative: 30
            }]);
        }));
    });
});


text:
package com.android.server.accounts;

import android.accounts.Account;
import android.accounts.AuthenticatorDescription;
import android.app.Notification;
import android.content.Context;
import android.content.pm.PackageManager;
import android.content.pm.RegisteredServicesCache.ServiceInfo;
import android.content.pm.RegisteredServicesCacheListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.UserHandle;
import android.test.AndroidTestCase;
import android.test.IsolatedContext;
import android.test.RenamingDelegatingContext;
import android.test.mock.MockContentResolver;
import android.test.mock.MockContext;
import android.test.mock.MockPackageManager;

import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;

public class AccountManagerServiceTest extends AndroidTestCase {
    private AccountManagerService mAms;

    @Override
    protected void setUp() throws Exception {
        final String filenamePrefix = "test.";
        MockContentResolver resolver = new MockContentResolver();
        RenamingDelegatingContext targetContextWrapper = new RenamingDelegatingContext(
                new MyMockContext(), // The context that most methods are delegated to
                getContext(), // The context that file methods are delegated to
                filenamePrefix);
        Context context = new IsolatedContext(resolver, targetContextWrapper);
        setContext(context);
        mAms = new MyAccountManagerService(getContext(),
                new MyMockPackageManager(), new MockAccountAuthenticatorCache());
    }

    public class AccountSorter implements Comparator<Account> {
        public int compare(Account object1, Account object2) {
            if (object1 == object2) return 0;
            if (object1 == null) return 1;
            if (object2 == null) return -1;
            int result = object1.type.compareTo(object2.type);
            if (result != 0) return result;
            return object1.name.compareTo(object2.name);
        }
    }

    public void testCheckAddAccount() throws Exception {
        Account a11 = new Account("account1", "type1");
        Account a21 = new Account("account2", "type1");
        Account a31 = new Account("account3", "type1");
        Account a12 = new Account("account1", "type2");
        Account a22 = new Account("account2", "type2");
        Account a32 = new Account("account3", "type2");
        mAms.addAccountExplicitly(a11, "p11", null);
        mAms.addAccountExplicitly(a12, "p12", null);
        mAms.addAccountExplicitly(a21, "p21", null);
        mAms.addAccountExplicitly(a22, "p22", null);
        mAms.addAccountExplicitly(a31, "p31", null);
        mAms.addAccountExplicitly(a32, "p32", null);

        Account[] accounts = mAms.getAccounts(null);
        Arrays.sort(accounts, new AccountSorter());
        assertEquals(6, accounts.length);
        assertEquals(a11, accounts[0]);
        assertEquals(a21, accounts[1]);
        assertEquals(a31, accounts[2]);
        assertEquals(a12, accounts[3]);
        assertEquals(a22, accounts[4]);
        assertEquals(a32, accounts[5]);

        accounts = mAms.getAccounts("type1" );
        Arrays.sort(accounts, new AccountSorter());
        assertEquals(3, accounts.length);
        assertEquals(a11, accounts[0]);
        assertEquals(a21, accounts[1]);
        assertEquals(a31, accounts[2]);

        mAms.removeAccountInternal(a21);

        accounts = mAms.getAccounts("type1" );
        Arrays.sort(accounts, new AccountSorter());
        assertEquals(2, accounts.length);
        assertEquals(a11, accounts[0]);
        assertEquals(a31, accounts[1]);
    }

    public void testPasswords() throws Exception {
        Account a11 = new Account("account1", "type1");
        Account a12 = new Account("account1", "type2");
        mAms.addAccountExplicitly(a11, "p11", null);
        mAms.addAccountExplicitly(a12, "p12", null);

        assertEquals("p11", mAms.getPassword(a11));
        assertEquals("p12", mAms.getPassword(a12));

        mAms.setPassword(a11, "p11b");

        assertEquals("p11b", mAms.getPassword(a11));
        assertEquals("p12", mAms.getPassword(a12));
    }

    public void testUserdata() throws Exception {
        Account a11 = new Account("account1", "type1");
        Bundle u11 = new Bundle();
        u11.putString("a", "a_a11");
        u11.putString("b", "b_a11");
        u11.putString("c", "c_a11");
        Account a12 = new Account("account1", "type2");
        Bundle u12 = new Bundle();
        u12.putString("a", "a_a12");
        u12.putString("b", "b_a12");
        u12.putString("c", "c_a12");
        mAms.addAccountExplicitly(a11, "p11", u11);
        mAms.addAccountExplicitly(a12, "p12", u12);

        assertEquals("a_a11", mAms.getUserData(a11, "a"));
        assertEquals("b_a11", mAms.getUserData(a11, "b"));
        assertEquals("c_a11", mAms.getUserData(a11, "c"));
        assertEquals("a_a12", mAms.getUserData(a12, "a"));
        assertEquals("b_a12", mAms.getUserData(a12, "b"));
        assertEquals("c_a12", mAms.getUserData(a12, "c"));

        mAms.setUserData(a11, "b", "b_a11b");
        mAms.setUserData(a12, "c", null);

        assertEquals("a_a11", mAms.getUserData(a11, "a"));
        assertEquals("b_a11b", mAms.getUserData(a11, "b"));
        assertEquals("c_a11", mAms.getUserData(a11, "c"));
        assertEquals("a_a12", mAms.getUserData(a12, "a"));
        assertEquals("b_a12", mAms.getUserData(a12, "b"));
        assertNull(mAms.getUserData(a12, "c"));
    }

    public void testAuthtokens() throws Exception {
        Account a11 = new Account("account1", "type1");
        Account a12 = new Account("account1", "type2");
        mAms.addAccountExplicitly(a11, "p11", null);
        mAms.addAccountExplicitly(a12, "p12", null);

        mAms.setAuthToken(a11, "att1", "a11_att1");
        mAms.setAuthToken(a11, "att2", "a11_att2");
        mAms.setAuthToken(a11, "att3", "a11_att3");
        mAms.setAuthToken(a12, "att1", "a12_att1");
        mAms.setAuthToken(a12, "att2", "a12_att2");
        mAms.setAuthToken(a12, "att3", "a12_att3");

        assertEquals("a11_att1", mAms.peekAuthToken(a11, "att1"));
        assertEquals("a11_att2", mAms.peekAuthToken(a11, "att2"));
        assertEquals("a11_att3", mAms.peekAuthToken(a11, "att3"));
        assertEquals("a12_att1", mAms.peekAuthToken(a12, "att1"));
        assertEquals("a12_att2", mAms.peekAuthToken(a12, "att2"));
        assertEquals("a12_att3", mAms.peekAuthToken(a12, "att3"));

        mAms.setAuthToken(a11, "att3", "a11_att3b");
        mAms.invalidateAuthToken(a12.type, "a12_att2");

        assertEquals("a11_att1", mAms.peekAuthToken(a11, "att1"));
        assertEquals("a11_att2", mAms.peekAuthToken(a11, "att2"));
        assertEquals("a11_att3b", mAms.peekAuthToken(a11, "att3"));
        assertEquals("a12_att1", mAms.peekAuthToken(a12, "att1"));
        assertNull(mAms.peekAuthToken(a12, "att2"));
        assertEquals("a12_att3", mAms.peekAuthToken(a12, "att3"));

        assertNull(mAms.peekAuthToken(a12, "att2"));
    }

    static public class MockAccountAuthenticatorCache implements IAccountAuthenticatorCache {
        private ArrayList<ServiceInfo<AuthenticatorDescription>> mServices;

        public MockAccountAuthenticatorCache() {
            mServices = new ArrayList<ServiceInfo<AuthenticatorDescription>>();
            AuthenticatorDescription d1 = new AuthenticatorDescription("type1", "p1", 0, 0, 0, 0);
            AuthenticatorDescription d2 = new AuthenticatorDescription("type2", "p2", 0, 0, 0, 0);
            mServices.add(new ServiceInfo<AuthenticatorDescription>(d1, null, 0));
            mServices.add(new ServiceInfo<AuthenticatorDescription>(d2, null, 0));
        }

        @Override
        public ServiceInfo<AuthenticatorDescription> getServiceInfo(
                AuthenticatorDescription type, int userId) {
            for (ServiceInfo<AuthenticatorDescription> service : mServices) {
                if (service.type.equals(type)) {
                    return service;
                }
            }
            return null;
        }

        @Override
        public Collection<ServiceInfo<AuthenticatorDescription>> getAllServices(int userId) {
            return mServices;
        }

        @Override
        public void dump(
                final FileDescriptor fd, final PrintWriter fout, final String[] args, int userId) {
        }

        @Override
        public void setListener(
                final RegisteredServicesCacheListener<AuthenticatorDescription> listener,
                final Handler handler) {
        }

		@Override
		public void invalidateCache(int userId) {
		}
    }

    static public class MyMockContext extends MockContext {
        @Override
        public int checkCallingOrSelfPermission(final String permission) {
            return PackageManager.PERMISSION_GRANTED;
        }
    }

    static public class MyMockPackageManager extends MockPackageManager {
        @Override
        public int checkSignatures(final int uid1, final int uid2) {
            return PackageManager.SIGNATURE_MATCH;
        }
    }

    static public class MyAccountManagerService extends AccountManagerService {
        public MyAccountManagerService(Context context, PackageManager packageManager,
                IAccountAuthenticatorCache authenticatorCache) {
            super(context, packageManager, authenticatorCache);
        }

        @Override
        protected void installNotification(final int notificationId, final Notification n, UserHandle user) {
        }

        @Override
        protected void cancelNotification(final int id, UserHandle user) {
        }
    }
}


text:
A library that simplifies [OpenAPI][openapi] integrations.  This library handles the minutiae of loading OpenAPI
documents *(local and remote)*, resolving references *(local, remote)*, building an object model and providing you with
a rich set of APIs for things like OpenAPI document validation, request/response validation, etc.  For more details on
the available APIs, please view the [API Documentation](https://github.com/apigee-127/sway/blob/master/docs/API.md).

`master` will always be built to support the latest release of OpenAPI, which right now is `3.x`.  Previous versions are
in their own respective `v{N}.x` branch:

* _3.x Support (WIP):_ `master`
* _2.x Support:_ [v2.x](https://github.com/apigee-127/sway/tree/v2.x)

## Project Badges

* Dependencies: [![Dependencies](https://david-dm.org/apigee-127/sway.svg)](https://david-dm.org/apigee-127/sway)
* Developer dependencies: [![Dev Dependencies](https://david-dm.org/apigee-127/sway/dev-status.svg)](https://david-dm.org/apigee-127/sway#info=devDependencies&view=table)
* Downloads: [![NPM Downloads Per Month](http://img.shields.io/npm/dm/sway.svg)](https://www.npmjs.org/package/sway)
* Gitter: [![Join the chat at https://gitter.im/apigee-127/sway](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/apigee-127/sway?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
* License: [![License](http://img.shields.io/npm/l/sway.svg)](https://github.com/apigee-127/sway/blob/master/LICENSE)
* Version: [![NPM Version](http://img.shields.io/npm/v/sway.svg)](https://www.npmjs.org/package/sway)

## Installation

sway is available for both Node.js and the browser.  Installation instructions for each environment are below.

### Browser

sway binaries for the browser are available in the `dist/` directory:

* [sway-standalone.js](https://raw.github.com/apigee-127/sway/master/dist/sway.js): _9,160kb_, full source  and source maps
* [sway-standalone-min.js](https://raw.github.com/apigee-127/sway/master/dist/sway-min.js): _864kb_, minified, compressed and no source map

**Note:** I realize these binaries are big and I'm working on making them smaller.  Unfortunately, some of this is out
of my control without rewriting some of the core features provided by third-party libraries currently contributing to
the size issue.

Of course, these links are for the master builds so feel free to download from the release of your choice.  Once you've
gotten them downloaded, to use the standalone binaries, your HTML include might look like this:

``` html
<!-- ... -->
<script src="sway.js"></script>
<!-- ... -->
```

### Node.js

Installation for Node.js applications can be done via [NPM][npm].

```
npm install sway --save
```

## Documentation

The documentation for this project can be found here: [/docs/README](/docs/README.md)

Of course, if you just want a quick link to the API documentation, that would be here:[/docs/API.md](/docs/API.md)

## Contributing

This project uses [Gulp][gulp] for building so `npm install -g gulp` once you clone this project.  Running `gulp` in the
project root will lint check the source code and run the unit tests.

[gulp]: http://gulpjs.com/
[openapi]: https://www.openapis.org/
[npm]: https://www.npmjs.org/


text:
#ifndef BIGINT_H
#define BIGINT_H

/**   @file bigint.h
      @author Mike Helmick
      @date 9/15/2013
      */

#include <string>
#include <vector>

using namespace std;

/**
  * Class representing a integer class capable of very large signed numbers.
  This BigInt class implements an infinitely long non-negative integer, with some
  mathematical operations possible:  addition, subtraction, multiplication,
  and division.

  BitInts can be initialized via a long, a string of digits, or a string
  of binary digits (0bxxxx).

  BigInts can be retrieved as a string of digits, or as a string of binary
  digits.
*/
class BigInt{

public:

  /**
    * Default constructor initializes to 0
    */
  BigInt();

  /**
    * Creates a new BigInt from a long integer
    */
  BigInt(long number);

  /**
    * Creates a new BigInt from a string of digits.
    * Or, if the string starts with 0b, then interpret as binary
    */
  BigInt(string number);

  /**
    * Create a new BigInt from another one.
    */
  BigInt(const BigInt& number);

  /*
   * @Return neg if this is less than that, zero if equal and 1 if this is greater than that.
   */
  int compareTo(const BigInt &that);

  /**
    * Return true if the sent BigInt has the same value.
    */
  bool isEqual(const BigInt &number);

  /**
    * Return true if 'this' < number
    */
  bool isLess(const BigInt &number);

  /**
    * Return true if 'this' > number
    */
  bool isGreater(const BigInt &number);

  /**
    * Return the Bigint as a string of digits or binary (0bxxxx)
    * With negative binary (0-bxxxx)
    */
  string getAsDigits();
  string getAsBinary();
  /**
    * Return the Bigint as a long.  Returns maxlong (minlong) if BigInt larger than
    * long supports.
    */
  long getAsLong();

  /**
    * Adds/subtract another Bigint to the current one and changes 'this' object.
    * ('this' - number) for subtraction
    * If subtraction would result in a negative value, set equal to 0.
    */
  void add(const BigInt &number);
  void subtract(const BigInt &number);

    /**
    * Multiply/divide another Bigint (rr long) to the current one and
    * changes 'this' object.
    * ('this' / number) for division
    */
  void multiply(const BigInt &number);
  void multiply(long number);
  void divide(const BigInt &number);

private:
  bool negative;
  // Each digit as base 10, least significant first.
  vector<int> digits;

  void init(string& number);
  string longToString(long number);
  int charToDigit(char charDigit);

  void adjustResultAndCarry(int &result, int &carry);

  int signedVectorCompare(bool lhsNegative, const vector<int> &lhs,
    bool rhsNegative, const vector<int> &rhs);
  int vectorCompareAbs(const vector<int> &lhs, const vector<int> &rhs);
  void vectorAdd(vector<int> &lhs, const vector<int> &rhs);
  void vectorSubtract(bool &lhsNegative, vector<int> &lhs,
      const bool &rhsNegative, const vector<int> &rhs);

  // debugging assistance
  void output(string name, const vector<int> &data);
};

#endif


text:
package i5.las2peer.services.ocd.centrality.measures;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.la4j.matrix.Matrix;
import org.la4j.vector.Vector;

import i5.las2peer.services.ocd.centrality.data.CentralityCreationLog;
import i5.las2peer.services.ocd.centrality.data.CentralityCreationType;
import i5.las2peer.services.ocd.centrality.data.CentralityMeasureType;
import i5.las2peer.services.ocd.centrality.utils.CentralityAlgorithm;
import i5.las2peer.services.ocd.centrality.utils.MatrixOperations;
import i5.las2peer.services.ocd.centrality.data.CentralityMap;
import i5.las2peer.services.ocd.graphs.CustomGraph;
import i5.las2peer.services.ocd.graphs.GraphType;
import y.base.Node;
import y.base.NodeCursor;

/**
 * Implementation of Eigenvector Centrality.
 * See: Bonacich, Phillip. 1972. Factoring and weighting approaches to status scores and clique identification.
 * @author Tobias
 *
 */
public class EigenvectorCentrality implements CentralityAlgorithm {

	public CentralityMap getValues(CustomGraph graph) throws InterruptedException {
		CentralityMap res = new CentralityMap(graph);
		res.setCreationMethod(new CentralityCreationLog(CentralityMeasureType.EIGENVECTOR_CENTRALITY, CentralityCreationType.CENTRALITY_MEASURE, this.getParameters(), this.compatibleGraphTypes()));

		NodeCursor nc = graph.nodes();
		// If the graph contains no edges
		if(graph.edgeCount() == 0) {
			while(nc.ok()) {
				Node node = nc.node();
				res.setNodeValue(node, 0);
				nc.next();
			}
			return res;
		}

		Matrix A = graph.getNeighbourhoodMatrix();
		Vector eigenvector = MatrixOperations.calculatePrincipalEigenvector(A);

		while(nc.ok()) {
			if(Thread.interrupted()) {
				throw new InterruptedException();
			}
			Node node = nc.node();
			res.setNodeValue(node, eigenvector.get(node.index()));
			nc.next();
		}
		return res;
	}

	@Override
	public Set<GraphType> compatibleGraphTypes() {
		Set<GraphType> compatibleTypes = new HashSet<GraphType>();
		return compatibleTypes;
	}

	@Override
	public CentralityMeasureType getCentralityMeasureType() {
		return CentralityMeasureType.EIGENVECTOR_CENTRALITY;
	}

	@Override
	public HashMap<String, String> getParameters() {
		return new HashMap<String, String>();
	}

	@Override
	public void setParameters(Map<String, String> parameters) throws IllegalArgumentException {
		if(parameters.size() > 0) {
			throw new IllegalArgumentException();
		}
	}
}


text:
module TransactionHelpers
  def uploaded_file
    if rails_present?
      ActionDispatch::Http::UploadedFile.new(:tempfile => '/tmp')
    else
      ::Rack::Multipart::UploadedFile.new(File.join(fixtures_dir, '/uploaded_file.txt'))
    end
  end

  def transaction_with_exception
    appsignal_transaction(:process_action_event => notification_event).tap do |o|
      o.set_tags('user_id' => 123)
      begin
        raise ArgumentError, 'oh no'
      rescue ArgumentError => exception
        exception.stub(:backtrace => [
          File.join(project_fixture_path, 'app/controllers/somethings_controller.rb:10').to_s,
          '/user/local/ruby/path.rb:8'
        ])
        o.set_exception(exception)
      end
    end
  end

  def regular_transaction
    appsignal_transaction(:process_action_event => notification_event)
  end

  def regular_transaction_with_x_request_start
    appsignal_transaction(
      :process_action_event => notification_event,
      'HTTP_X_REQUEST_START' => "t=#{((fixed_time - 0.04) * 1000).to_i}"
    )
  end

  def slow_transaction(args={})
    appsignal_transaction(
      {
        :process_action_event => notification_event(
          :start => fixed_time,
          :ending => fixed_time + Appsignal.config[:slow_request_threshold] / 999.99
        )
      }.merge(args)
    )
  end

  def slower_transaction(args={})
    appsignal_transaction(
      {
        :process_action_event => notification_event(
          :start => fixed_time,
          :ending => fixed_time + Appsignal.config[:slow_request_threshold] / 499.99
        )
      }.merge(args)
    )
  end

  def background_job_transaction(args={}, payload=background_env_with_data)
    Appsignal::Transaction.create(
      '1',
      Appsignal::Transaction::BACKGROUND_JOB,
      Appsignal::Transaction::GenericRequest.new({
        'SERVER_NAME' => 'localhost',
        'action_dispatch.routes' => 'not_available'
      }.merge(args))
    )
  end

  def appsignal_transaction(args={})
    process_action_event = args.delete(:process_action_event)
    args.delete(:events) || [
      notification_event(:name => 'query.mongoid')
    ]
    exception = args.delete(:exception)
    Appsignal::Transaction.create(
      '1',
      args.delete(:namespace) || Appsignal::Transaction::HTTP_REQUEST,
      {
        'HTTP_USER_AGENT' => 'IE6',
        'SERVER_NAME' => 'localhost',
        'action_dispatch.routes' => 'not_available'
      }.merge(args)
    ).tap do |o|
      o.set_action(process_action_event.name)
      o.set_exception(exception) if exception
    end
  end
end


text:
package io.joynr.exceptions;

/**
 * Joynr exception to report errors during discovery.
 */
public class DiscoveryException extends JoynrRuntimeException {
    private static final long serialVersionUID = -5333394188396893835L;

    /**
     * Constructor for a DiscoveryException with detail message.
     *
     * @param message further description of the reported discovery error
     */
    public DiscoveryException(String message) {
        super(message);
    }
}


text:
<?php

namespace common\core;

use yii\base\Module;

class ModuleBase extends Module
{

    public function init()
    {
        $class = new \ReflectionClass($this);
        $appId = \Yii::$app->id;

        $this->controllerNamespace = $class->getNamespaceName() . '\\' . $appId . '\\controllers';
        $this->setBasePath(dirname($class->getFileName()) . DIRECTORY_SEPARATOR . $appId);

        parent::init();
    }

}


text:
// ::color::set::blue( c, val )

#include "../place/place.hpp"

 namespace color
  {
   namespace set
    {
     template< typename tag_name >
      inline
      void
      blue
       (
                  ::color::model< ::color::category::rgb<tag_name> >                                   & color_parameter,
        typename  ::color::model< ::color::category::rgb<tag_name> >::component_input_const_type         component_parameter
       )
       {
        typedef ::color::category::rgb<tag_name>  category_type;
        enum{ blue_p  = ::color::place::_internal::blue<category_type>::position_enum };

        color_parameter.template set<blue_p>( component_parameter );
       }

    }
  }

#endif


text:
package org.osgi.service.transaction.control;

/**
 * Resources that can integrate with local transactions should do so using this
 * interface
 */
public interface LocalResource {

	/**
	 * Commit the resource
	 *
	 * @throws TransactionException if an error occurs while committing,
	 */
	void commit() throws TransactionException;

	/**
	 * Roll back the resource
	 *
	 * @throws TransactionException if an error occurs while rolling back
	 */
	void rollback() throws TransactionException;
}


text:
import Abstract from './abstract-mongo';
// noinspection JSUnresolvedVariable
import {MongoClient} from 'mongodb';
import _ from 'underscore';

// persist the data to disk
MongoClient.persist = 'tmp/mongo.js';
const url = 'mongodb://localhost:27017/crm_js_v_0_0_1';
const collection = 'abstract_mongo';

const makeReject = (db, reject) => {
  return () => {
    db && db.close();
    reject.apply(arguments);
  };
};

afterAll(() => {
  return new Promise((resolve) => {
    MongoClient.connect(url, {}).then(
      (db) => db.collection(collection).drop().then(() => {
        db.close();
        resolve();
      })
    );
  });
});

it('Create single element', () => {
  return new Promise((resolve, reject) => {
    MongoClient.connect(url, {}).then((db) => {
      const abstractObject = new Abstract(db.collection(collection));
      const element = {name: 'Test'};

      abstractObject.create(element).then(
        (id) => {
          // Check that id is instance of MongoDB ObjectId
          expect(id.length).toBe(24);

          db.close();
          resolve();
        },
        makeReject(db, reject)
      );
    }, makeReject(null, reject));
  });
});

it('Read elements', () => {
  return new Promise((resolve, reject) => {
    MongoClient.connect(url, {}).then((db) => {
      const abstractObject = new Abstract(db.collection(collection));
      const promises = [
        abstractObject.create({name: 'Test 0'}),
        abstractObject.create({name: 'Test 1'}),
        abstractObject.create({name: 'Test 2'}),
        abstractObject.create({name: 'Test 3'}),
        abstractObject.create({name: 'Test 4'}),
      ];

      Promise.all(promises).then(
        (ids) => abstractObject.read().then((result) => {
            _.chain(ids)
              .map((id) => id)
              .map((id) => {
                  let found = _.findWhere(result, {id: id});

                  expect(found).toBeInstanceOf(Object);
                }
              );

            db.close();
            resolve();
          },
          makeReject(db, reject)
        ),
        makeReject(db, reject)
      );
    }, makeReject(null, reject));
  });
});

it('Update single element', () => {
  return new Promise((resolve, reject) => {
    MongoClient.connect(url, {}).then((db) => {
      const abstractObject = new Abstract(db.collection(collection));
      _.extend(abstractObject._fields, {phones: {id: 'phones'}});

      let element = {name: 'Test', phones: ['999 999 9999']};
      abstractObject.create(element).then(
        (id) => {
          let updatedElement = {
            name: 'Test updated',
          };

          abstractObject.update(id, updatedElement).then(
            () => {
              abstractObject.read({id}).then((result) => {
                  let resultElement = _.extend(element, updatedElement);
                  expect(_.first(result)).toMatchObject(resultElement);
                  db.close();
                  resolve();
                },
                makeReject(db, reject)
              );
            },
            makeReject(db, reject)
          );
        },
        makeReject(db, reject)
      );
    }, makeReject(null, reject));
  });
});

it('Replace single element', () => {
  return new Promise((resolve, reject) => {
    MongoClient.connect(url, {}).then((db) => {
      const abstractObject = new Abstract(db.collection(collection));
      _.extend(abstractObject._fields, {phones: {id: 'phones'}});

      let element = {name: 'Test', phones: ['999 999 9999']};
      abstractObject.create(element).then(
        (id) => {
          element = {name: 'Test replaced'};

          abstractObject.replace(id, element).then(
            () => {
              abstractObject.read({id}).then((result) => {
                  expect(_.first(result)).toMatchObject(element);
                  db.close();
                  resolve();
                },
                makeReject(db, reject)
              );
            },
            makeReject(db, reject)
          );
        },
        makeReject(db, reject)
      );
    }, makeReject(null, reject));
  });
});

it('Remove single element', () => {
  return new Promise((resolve, reject) => {
    MongoClient.connect(url, {}).then((db) => {
      const abstractObject = new Abstract(db.collection(collection));

      let element = {name: 'Test', phones: ['999 999 9999']};
      abstractObject.create(element).then(
        (id) => {
          element = {name: 'Test replaced'};

          abstractObject.remove(id).then(
            () => {
              abstractObject.read({id}).then((result) => {
                  expect(result).toMatchObject([]);
                  db.close();
                  resolve();
                },
                makeReject(db, reject)
              );
            },
            makeReject(db, reject)
          );
        },
        makeReject(db, reject)
      );
    }, makeReject(null, reject));
  });
});


text:
#   Copyright 2015 Dejan D. M. Milosavljevic
#
#   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.

import os
import subprocess

import nucleotide
import nucleotide.component
import nucleotide.component.function
import nucleotide.component.windows._common.python

def _python_python27_msvc12_CPPPATH( P_list ):
    I_result = os.getenv('PYTHON27_MSVC12_INCLUDE')
    if( None == I_result ):
        return nucleotide.component.windows._common.python._python27_default_CPPPATH( P_list )
    return [ I_result ]

def _python_python27_msvc12_LIBPATH( P_list ):
    I_result = os.getenv('PYTHON27_MSVC12_LIBPATH')
    if( None == I_result ):
        return nucleotide.component.windows._common.python._python27_default_LIBPATH( P_list )
    return [ I_result ]

atom_python27_msvc_12 = {
    'platform' : {
        'host'  : 'Windows',
        'guest' : 'Windows'
    },
    'cc' : {
        'vendor' : 'Microsoft',
        'name'   : 'msvc',
        'version': '12'
    },
    'config' : {
            'CPPPATH': _python_python27_msvc12_CPPPATH,
            'LIBPATH': _python_python27_msvc12_LIBPATH,
            'LIBS'   : [ 'python27.lib' ]
    },
    'name' : 'python27:msvc12',
    'class':  [ 'python', 'python:default', 'python27:default', 'python27:msvc12' ]
}

def _python_python35_msvc12_CPPPATH( P_list ):
    I_result = os.getenv('PYTHON35_MSVC12_INCLUDE')
    if( None == I_result ):
        return nucleotide.component.windows._common.python._python35_default_CPPPATH( P_list )
    return [ I_result ]

def _python_python35_msvc12_LIBPATH( P_list ):
    I_result = os.getenv('PYTHON35_MSVC12_LIBPATH')
    if( None == I_result ):
        return nucleotide.component.windows._common.python._python35_default_LIBPATH( P_list )
    return [ I_result ]

atom_python35_msvc_12 = {
    'platform' : {
        'host'  : 'Windows',
        'guest' : 'Windows'
    },
    'cc' : {
        'vendor': 'Microsoft',
        'name': 'msvc',
        'version': '12'
    },
    'config' : {
            'CPPPATH': _python_python35_msvc12_CPPPATH,
            'LIBPATH': _python_python35_msvc12_LIBPATH,
            'LIBS'   : [ 'python35.lib' ]
    },
    'name' : 'python35:msvc12',
    'class':  [ 'python', 'python:default', 'python35:default', 'python35:msvc12' ]
}

class Python:
    def __init__( ):
        pass

    @staticmethod
    def extend( P_option ) :
        nucleotide.component.function.extend( P_option, 'python27:msvc',    atom_python27_msvc_12 )
        nucleotide.component.function.extend( P_option, 'python35:msvc',    atom_python35_msvc_12 )

    def check():

        nucleotide.component.function.check__env( 'PYTHONPATH' )

        nucleotide.component.function.check__env( 'PYTHON27_MSVC12_INCLUDE' )
        nucleotide.component.function.check__env( 'PYTHON27_MSVC12_LIBPATH' )
        nucleotide.component.function.check__env( 'PYTHON27_MSVC12_VERSION' )

        nucleotide.component.function.check__env( 'PYTHON35_MSVC12_INCLUDE' )
        nucleotide.component.function.check__env( 'PYTHON35_MSVC12_LIBPATH' )
        nucleotide.component.function.check__env( 'PYTHON35_MSVC12_VERSION' )


text:
ALTER TABLE atomic.events RENAME TO events_010;

-- Create 0.11.0 events table
CREATE TABLE atomic.events (
  -- App
  app_id varchar(255) encode ZSTD,
  platform varchar(255) encode ZSTD,
  -- Date/time
  etl_tstamp timestamp  encode ZSTD,
  collector_tstamp timestamp not null encode RAW,
  dvce_created_tstamp timestamp encode ZSTD,
  -- Event
  event varchar(128) encode ZSTD,
  event_id char(36) not null unique encode ZSTD,
  txn_id int encode ZSTD,
  -- Namespacing and versioning
  name_tracker varchar(128) encode ZSTD,
  v_tracker varchar(100) encode ZSTD,
  v_collector varchar(100) encode ZSTD not null,
  v_etl varchar(100) encode ZSTD not null,
  -- User and visit
  user_id varchar(255) encode ZSTD,
  user_ipaddress varchar(128) encode ZSTD,
  user_fingerprint varchar(128) encode ZSTD,
  domain_userid varchar(128) encode ZSTD,
  domain_sessionidx int encode ZSTD,
  network_userid varchar(128) encode ZSTD,
  -- Location
  geo_country char(2) encode ZSTD,
  geo_region char(3) encode ZSTD,
  geo_city varchar(75) encode ZSTD,
  geo_zipcode varchar(15) encode ZSTD,
  geo_latitude double precision encode ZSTD,
  geo_longitude double precision encode ZSTD,
  geo_region_name varchar(100) encode ZSTD,
  -- IP lookups
  ip_isp varchar(100) encode ZSTD,
  ip_organization varchar(128) encode ZSTD,
  ip_domain varchar(128) encode ZSTD,
  ip_netspeed varchar(100) encode ZSTD,
  -- Page
  page_url varchar(4096) encode ZSTD,
  page_title varchar(2000) encode ZSTD,
  page_referrer varchar(4096) encode ZSTD,
  -- Page URL components
  page_urlscheme varchar(16) encode ZSTD,
  page_urlhost varchar(255) encode ZSTD,
  page_urlport int encode ZSTD,
  page_urlpath varchar(3000) encode ZSTD,
  page_urlquery varchar(6000) encode ZSTD,
  page_urlfragment varchar(3000) encode ZSTD,
  -- Referrer URL components
  refr_urlscheme varchar(16) encode ZSTD,
  refr_urlhost varchar(255) encode ZSTD,
  refr_urlport int encode ZSTD,
  refr_urlpath varchar(6000) encode ZSTD,
  refr_urlquery varchar(6000) encode ZSTD,
  refr_urlfragment varchar(3000) encode ZSTD,
  -- Referrer details
  refr_medium varchar(25) encode ZSTD,
  refr_source varchar(50) encode ZSTD,
  refr_term varchar(255) encode ZSTD,
  -- Marketing
  mkt_medium varchar(255) encode ZSTD,
  mkt_source varchar(255) encode ZSTD,
  mkt_term varchar(255) encode ZSTD,
  mkt_content varchar(500) encode ZSTD,
  mkt_campaign varchar(255) encode ZSTD,
  -- Custom structured event
  se_category varchar(1000) encode ZSTD,
  se_action varchar(1000) encode ZSTD,
  se_label varchar(4096) encode ZSTD,
  se_property varchar(1000) encode ZSTD,
  se_value double precision encode ZSTD,
  -- Ecommerce
  tr_orderid varchar(255) encode ZSTD,
  tr_affiliation varchar(255) encode ZSTD,
  tr_total dec(18,2) encode ZSTD,
  tr_tax dec(18,2) encode ZSTD,
  tr_shipping dec(18,2) encode ZSTD,
  tr_city varchar(255) encode ZSTD,
  tr_state varchar(255) encode ZSTD,
  tr_country varchar(255) encode ZSTD,
  ti_orderid varchar(255) encode ZSTD,
  ti_sku varchar(255) encode ZSTD,
  ti_name varchar(255) encode ZSTD,
  ti_category varchar(255) encode ZSTD,
  ti_price dec(18,2) encode ZSTD,
  ti_quantity int encode ZSTD,
  -- Page ping
  pp_xoffset_min int encode ZSTD,
  pp_xoffset_max int encode ZSTD,
  pp_yoffset_min int encode ZSTD,
  pp_yoffset_max int encode ZSTD,
  -- User Agent
  useragent varchar(1000) encode ZSTD,
  -- Browser
  br_name varchar(50) encode ZSTD,
  br_family varchar(50) encode ZSTD,
  br_version varchar(50) encode ZSTD,
  br_type varchar(50) encode ZSTD,
  br_renderengine varchar(50) encode ZSTD,
  br_lang varchar(255) encode ZSTD,
  br_features_pdf boolean encode ZSTD,
  br_features_flash boolean encode ZSTD,
  br_features_java boolean encode ZSTD,
  br_features_director boolean encode ZSTD,
  br_features_quicktime boolean encode ZSTD,
  br_features_realplayer boolean encode ZSTD,
  br_features_windowsmedia boolean encode ZSTD,
  br_features_gears boolean encode ZSTD,
  br_features_silverlight boolean encode ZSTD,
  br_cookies boolean encode ZSTD,
  br_colordepth varchar(12) encode ZSTD,
  br_viewwidth int encode ZSTD,
  br_viewheight int encode ZSTD,
  -- Operating System
  os_name varchar(50) encode ZSTD,
  os_family varchar(50)  encode ZSTD,
  os_manufacturer varchar(50)  encode ZSTD,
  os_timezone varchar(255)  encode ZSTD,
  -- Device/Hardware
  dvce_type varchar(50)  encode ZSTD,
  dvce_ismobile boolean encode ZSTD,
  dvce_screenwidth int encode ZSTD,
  dvce_screenheight int encode ZSTD,
  -- Document
  doc_charset varchar(128) encode ZSTD,
  doc_width int encode ZSTD,
  doc_height int encode ZSTD,

  -- Currency
  tr_currency char(3) encode ZSTD,
  tr_total_base dec(18, 2) encode ZSTD,
  tr_tax_base dec(18, 2) encode ZSTD,
  tr_shipping_base dec(18, 2) encode ZSTD,
  ti_currency char(3) encode ZSTD,
  ti_price_base dec(18, 2) encode ZSTD,
  base_currency char(3) encode ZSTD,

  -- Geolocation
  geo_timezone varchar(64) encode ZSTD,

  -- Click ID
  mkt_clickid varchar(128) encode ZSTD,
  mkt_network varchar(64) encode ZSTD,

  -- ETL tags
  etl_tags varchar(500) encode ZSTD,

  -- Time event was sent
  dvce_sent_tstamp timestamp encode ZSTD,

  -- Referer
  refr_domain_userid varchar(128) encode ZSTD,
  refr_dvce_tstamp timestamp encode ZSTD,

  -- Session ID
  domain_sessionid char(128) encode ZSTD,

  -- Derived timestamp
  derived_tstamp timestamp encode ZSTD,

  -- Event schema
  event_vendor varchar(1000) encode ZSTD,
  event_name varchar(1000) encode ZSTD,
  event_format varchar(128) encode ZSTD,
  event_version varchar(128) encode ZSTD,

    -- Event fingerprint
    event_fingerprint varchar(128) encode ZSTD,

    -- True timestamp
    true_tstamp timestamp encode ZSTD,

    CONSTRAINT event_id_0110_pk PRIMARY KEY(event_id)
)
DISTSTYLE KEY
DISTKEY (event_id)
SORTKEY (collector_tstamp);

-- Now copy into new from events_old
INSERT INTO atomic.events
    SELECT
    *
    FROM atomic.events_010;

COMMENT ON TABLE "atomic"."events" IS '0.11.0';


text:
id: 7431
title: 'I'm in a book!'
date: 2012-09-18T08:26:49+00:00
author: Vicki
layout: post
guid: http://blog.vickiboykis.com/wlb/?p=7431
permalink: /2012/09/im-in-a-book/
categories:
  - Uncategorized
tags:
  - books
  - living jewishly
  - writing
---
[](https://raw.githubusercontent.com/veekaybee/wlb/gh-pages/assets/images/2012/09/Screen-shot-2012-09-18-at-8.11.23-AM.png)

Not my own, yet, but still, just in time for Rosh Hashana, I’m legit published.  Along with Kate, Farrah, and a bunch of other talented people from all over the country, writing about what it means to be Jewish to them, from all sorts of angles.   All credit for the hard work of collecting our scribbles and actually pushing this thing through goes to Stefanie :).

Blurb:

> **“**[The book] is a collection of personal essays and memoirs from Jewish 20- and 30-somethings from across the country. Each contributor brings a unique perspective as they tell their self-defining Jewish story.”
>
> _At once confrontational, comforting, and hilarious this is the definitive 'Who am I? and why am I?' book for Jews of our generation. I can only hope to one day contribute to a collection this rigorous, this touching, and this important for the question of our identity as Jews.__"_ –Mayim Bialik
>
> _“I’m not a Jew…I’m just Jew-ish.” – Vicki Boykis_

Can you guess what my self-defining Jewish story is about?  If you guessed medical anxieties or God’s wrath, you’re a great guesser, but that’s not it.

 Other, less stupid stories include: “Converted to Reform” by Rabbi Julie Pelc Adler, “The Rumors of Her Death” by Libby Ellis Lowe, and “A New Kind of Jewish Geography” by Perry Teicher, about the Jews of the CIS republics.

Website is here. Book is available for purchase here.


text:
namespace gpu {

GLContextVirtual::GLContextVirtual(
    gfx::GLShareGroup* share_group,
    gfx::GLContext* shared_context,
    base::WeakPtr<gles2::GLES2Decoder> decoder)
  : GLContext(share_group),
    shared_context_(shared_context),
    display_(NULL),
    decoder_(decoder) {
}

gfx::Display* GLContextVirtual::display() {
  return display_;
}

bool GLContextVirtual::Initialize(
    gfx::GLSurface* compatible_surface, gfx::GpuPreference gpu_preference) {
  SetGLStateRestorer(new GLStateRestorerImpl(decoder_));

  display_ = static_cast<gfx::Display*>(compatible_surface->GetDisplay());

  // Virtual contexts obviously can't make a context that is compatible
  // with the surface (the context already exists), but we do need to
  // make a context current for SetupForVirtualization() below.
  if (!IsCurrent(compatible_surface)) {
    if (!shared_context_->MakeCurrent(compatible_surface)) {
      // This is likely an error. The real context should be made as
      // compatible with all required surfaces when it was created.
      LOG(ERROR) << "Failed MakeCurrent(compatible_surface)";
      return false;
    }
  }

  shared_context_->SetupForVirtualization();
  shared_context_->MakeVirtuallyCurrent(this, compatible_surface);
  return true;
}

void GLContextVirtual::Destroy() {
  shared_context_->OnReleaseVirtuallyCurrent(this);
  shared_context_ = NULL;
  display_ = NULL;
}

bool GLContextVirtual::MakeCurrent(gfx::GLSurface* surface) {
  if (decoder_.get())
    return shared_context_->MakeVirtuallyCurrent(this, surface);

  LOG(ERROR) << "Trying to make virtual context current without decoder.";
  return false;
}

void GLContextVirtual::ReleaseCurrent(gfx::GLSurface* surface) {
  if (IsCurrent(surface)) {
    shared_context_->OnReleaseVirtuallyCurrent(this);
    shared_context_->ReleaseCurrent(surface);
  }
}

bool GLContextVirtual::IsCurrent(gfx::GLSurface* surface) {
  // If it's a real surface it needs to be current.
  if (surface &&
      !surface->IsOffscreen())
    return shared_context_->IsCurrent(surface);

  // Otherwise, only insure the context itself is current.
  return shared_context_->IsCurrent(NULL);
}

void* GLContextVirtual::GetHandle() {
  return shared_context_->GetHandle();
}

void GLContextVirtual::OnSetSwapInterval(int interval) {
  shared_context_->SetSwapInterval(interval);
}

std::string GLContextVirtual::GetExtensions() {
  return shared_context_->GetExtensions();
}

bool GLContextVirtual::GetTotalGpuMemory(size_t* bytes) {
  return shared_context_->GetTotalGpuMemory(bytes);
}

void GLContextVirtual::SetSafeToForceGpuSwitch() {
  // TODO(ccameron): This will not work if two contexts that disagree
  // about whether or not forced gpu switching may be done both share
  // the same underlying shared_context_.
  return shared_context_->SetSafeToForceGpuSwitch();
}

bool GLContextVirtual::WasAllocatedUsingRobustnessExtension() {
  return shared_context_->WasAllocatedUsingRobustnessExtension();
}

void GLContextVirtual::SetUnbindFboOnMakeCurrent() {
  shared_context_->SetUnbindFboOnMakeCurrent();
}

GLContextVirtual::~GLContextVirtual() {
  Destroy();
}

}  // namespace gpu


text:
const { expect } = require('chai');
const addEnvironmentPermission = require('api/mutations/addEnvironmentPermission');
const { getToken } = require('core/profile');
const { defineEntryAs } = require('core/permission');
const { PRIVATE } = require('constants/permissions/pieces');
const { permissionModel, profileModel } = require('models');
const { MUTATION_RELATION } = require('constants/permissions/values');
const { PRIVATE_PROFILE } = require('constants/permissions/entries');
const { RELATION } = require('constants/permissions/types');

describe('Add environment permission', () => {

    const user = require('../../../envs/user')();
    before(user.before);
    after(user.after);

    it('add', () => {

        return profileModel.get({ id: user.id })
            .then(defineEntryAs(PRIVATE))
            .then(p => addEnvironmentPermission.resolve(null, {
                token: getToken({ profile: p }), permission: {
                    value: MUTATION_RELATION,
                    entry: PRIVATE_PROFILE
                }
            }).then(() => permissionModel.get({ profileId: user.id, types: [RELATION] }).then(permissions => {
                expect(permissions.length).to.equal(1);
            })).then(() => permissionModel.remove({ profileId: user.id })));

    });

});


text:
Title: JS Drip #1 Параметры по умолчанию в Javascript
Date: 2014-12-22 22:56
Tags: links, js, jsdrip
Slug: js-drip1
Lang: ru
Category: Translations
Authors: shamcode
Summary: Вольный перевод Js Drip #1 Default Parameters in JavaScript

Вольный перевод [Js Drip #1 Default Parameters in JavaScript](http://us6.campaign-archive1.com/?u=2cc20705b76fa66ab84a6634f&id=ce9ce7921e)

Такие языки как Ruby, CoffeeScript и будущие версии Javascript [\[1\]][1] позволяют задавать параметры по умолчанию при
определении функции. Это выглядит примерно так:

```js
function myFunc(param1, param2 = "second string") {
    console.log(param1, param2);
}

// Выведет: "first string" и "second string"
myFunc("first string");

// Выведет: "first string" и "second string version 2"
myFunc("first string", "second string version 2");
```

Увы, эта конструкция не доступна в текущей версии Javscript.  Что мы можем сделать, чтобы достичь такого поведения
с нынешними возможностями?

Простейшее решение выглядит так:

```js
function myFunc(param1, param2) {
    if (param2 === undefined) {
        param2 = "second string";
    }

    console.log(param1, param2);
}

// Выведет: "first string" и "second string version 2"
myFunc("first string", "second string version 2");
```

Этот прием зависит от того факта, что параметр пропущеный во время вызова всегда равен undefined. И это хорошее решение,
 если у вас есть только один параметр. Но что делать, если у вас их несколько?

В этом случае вам, вероятно, следует передавать в параметре объект, так как это дает преимущество, т.к. необходимо
явно называть все, что вы хотите передать. И если вы передаете в качестве параметра объект, то имеет смысл объявить
параметры по умолчанию таким же образом.

```js
function myFunc(paramObject) {
    var defaultParams = {
        param1: "first string",
        param2: "second string",
        param3: "third string"
    };

    var finalParams = defaultParams;

    // Мы перебираем все свойства paramObject
    for (var key in paramObject) {
        // Если текущее свойство не было унаследовано, то обрабатываем
        if (paramObject.hasOwnProperty(key)) {
            // Если текущее свойство определено,
            // добавляем его в finalParams
            if (paramObject[key] !== undefined) {
                finalParams[key] = defaultParams[key];
            }
        }
    }

    console.log(finalParams.param1,
                finalParams.param2,
                finalParams.param3);
}
```

Это немного громоздко, так что если вы часто используете эту схему, то имеет смысл извлечь перебор и логику фильтрации
в отдельную функцию. К счастью, умные люди, которые пишут JQuery и underscore, сделали это в соответствующих extend
методах. [\[2\]][2] [\[3\]][3]

Вот обновленная версия, которая использует метод extend библиотеки underscore для достижения того же результата.

```js
function myFunc(paramObject) {
    var defaultParams = {
        param1: "first string",
        param2: "second string",
        param3: "third string"
    };

    var finalParams = _.extend(defaultParams, paramObject);

    console.log(finalParams.param1,
                finalParams.param2,
                finalParams.param3);
}

// Вывод:
// "My own string" и "second string" и "third string"
myFunc({param1: "My own string"});
```
Вот так вы можете использовать параметры по умолчанию в текущих версиях JavaScript.

###Ссылки:
1. [Harmony of Dreams Come True, by Brendan Eich][1]
2. [Underscore's extend method][2]
3. [jQuery's extend method][3]

[1]: https://brendaneich.com/2012/10/harmony-of-dreams-come-true/ (Harmony of Dreams Come True, by Brendan Eich)
[2]: http://underscorejs.org/#extend (Underscore's extend method)
[3]: http://api.jquery.com/jQuery.extend/ (jQuery's extend method)


text:
::Rails.application.routes.draw do
  devise_for :users, :class_name => "::Trax::User"
  ActiveAdmin.routes(self)
end

::Trax::Backend::Engine.routes.draw do
  devise_for :users, :class_name => "::Trax::User"
  ActiveAdmin.routes(self)
end


text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<title>Wedo</title>
	<meta name="description" content="WeDo is a simple, online to-do list.">
	<meta name="author" content="Maeb">

	<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

	<link rel="stylesheet" href="../stylesheets/base.css">
	<link rel="stylesheet" href="../stylesheets/skeleton.css">
	<link rel="stylesheet" href="../stylesheets/layout.css">

< WEDO

Login

If you already have an account

Login

			<input class="four columns offset-by-four" id="email" type="email" placeholder="E-mail">
			<input class="four columns" id="password" type="password" placeholder="Password">
			<button class="four columns offset-by-six half-top add-bottom" id="signin_button">login</button>

This web application was created by Maeb


text:
using System.Management.Automation;
using Microsoft.SharePoint.Client;
using SharePointPnP.PowerShell.CmdletHelpAttributes;
using SharePointPnP.PowerShell.Commands.Base.PipeBinds;

namespace SharePointPnP.PowerShell.Commands.Principals
{
    [Cmdlet(VerbsCommon.Add, "PnPUserToGroup")]
    [CmdletHelp("Adds a user to a group",
        Category = CmdletHelpCategory.Principals)]
    [CmdletExample(
        Code = @"PS:> Add-PnPUserToGroup -LoginName user@company.com -Identity 'Marketing Site Members'",
		Remarks = @"Add the specified user to the group ""Marketing Site Members""",
        SortOrder = 1)]
    [CmdletExample(
        Code = @"PS:> Add-PnPUserToGroup -LoginName user@company.com -Identity 5",
        Remarks = "Add the specified user to the group with Id 5",
        SortOrder = 2)]
    public class AddUserToGroup : PnPWebCmdlet
    {

        [Parameter(Mandatory = true, HelpMessage = "The login name of the user", ParameterSetName = "Internal")]
        public string LoginName;

        [Parameter(Mandatory = true, HelpMessage = "The group id, group name or group object to add the user to.", ValueFromPipeline = true, ParameterSetName = "Internal")]
#if !ONPREMISES
        [Parameter(Mandatory = true, HelpMessage = "The group id, group name or group object to add the user to.", ValueFromPipeline = true, ParameterSetName = "External")]
#endif
        public GroupPipeBind Identity;

#if !ONPREMISES
        [Parameter(Mandatory = true, HelpMessage = "The email address of the user", ParameterSetName = "External")]
        public string EmailAddress;

        [Parameter(Mandatory = false, ParameterSetName = "External")]
        public SwitchParameter SendEmail;

        [Parameter(Mandatory = false, ParameterSetName = "External")]
        public string EmailBody = "Site shared with you.";
#endif
        protected override void ExecuteCmdlet()
        {
            var group = Identity.GetGroup(SelectedWeb);
#if !ONPREMISES
            if (ParameterSetName == "External")
            {
                group.InviteExternalUser(EmailAddress, SendEmail, EmailBody);
            }
            else
            {
                SelectedWeb.AddUserToGroup(group, LoginName);
            }
#else
            SelectedWeb.AddUserToGroup(group, LoginName);
#endif
        }
    }
}


text:
There are several ways of installing this package.

## Install from VS Code (Recommended)

Open **vscode** editor, then search `markdown-preview-enhanced` in `Extensions`, then click `Install` button.

![screen shot 2017-07-14 at 12 23 32 am](https://user-images.githubusercontent.com/1908863/28199365-bb03a570-682a-11e7-8f65-d7d2b258d583.png)

## Install from GitHub

- Download `markdown-preview-enhanced-*.vsix` file from [Releases](https://github.com/shd101wyy/vscode-markdown-preview-enhanced/releases).
- Open **vscode**, run `Extension: Install from VSIX`, then choose the `*.vsix` file you just downloaded.

[➔ Usages](usages.md)


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Patellaria melaleuca Müll. Arg.

### Remarks
null


text:
package org.mongodb.morphia.mapping.codec;

import org.bson.BsonReader;
import org.bson.BsonType;
import org.bson.BsonWriter;
import org.bson.codecs.Codec;
import org.bson.codecs.DecoderContext;
import org.bson.codecs.EncoderContext;
import org.bson.codecs.configuration.CodecConfigurationException;
import org.bson.codecs.pojo.PropertyCodecRegistry;
import org.bson.codecs.pojo.TypeData;
import org.bson.codecs.pojo.TypeWithTypeParameters;

import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

@SuppressWarnings("unchecked")
class MorphiaMapPropertyCodecProvider extends MorphiaPropertyCodecProvider {
    @Override
    public <T> Codec<T> get(final TypeWithTypeParameters<T> type, final PropertyCodecRegistry registry) {
        if (Map.class.isAssignableFrom(type.getType())) {
            final List<? extends TypeWithTypeParameters<?>> typeParameters = type.getTypeParameters();
            TypeWithTypeParameters<?> keyType = getType(typeParameters, 0);
            final TypeWithTypeParameters<?> valueType = getType(typeParameters, 1);

            try {
                return new MapCodec(type.getType(), keyType.getType(), registry.get(valueType));
            } catch (CodecConfigurationException e) {
                if (valueType.getType().equals(Object.class)) {
                    try {
                        return (Codec<T>) registry.get(TypeData.builder(Map.class).build());
                    } catch (CodecConfigurationException e1) {
                        // Ignore and return original exception
                    }
                }
                throw e;
            }
        } else if (Enum.class.isAssignableFrom(type.getType())) {
            return new EnumCodec(type.getType());
        }
        return null;
    }

    private static class MapCodec<K, V> implements Codec<Map<K, V>> {
        private final Class<Map<K, V>> encoderClass;
        private Class<K> keyType;
        private final Codec<V> codec;

        MapCodec(final Class<Map<K, V>> encoderClass, final Class<K> keyType, final Codec<V> codec) {
            this.encoderClass = encoderClass;
            this.keyType = keyType;
            this.codec = codec;
        }

        @Override
        public void encode(final BsonWriter writer, final Map<K, V> map, final EncoderContext encoderContext) {
            writer.writeStartDocument();
            for (final Entry<K, V> entry : map.entrySet()) {
                final K key = entry.getKey();
                writer.writeName((String) Conversions.convert(key, String.class));
                if (entry.getValue() == null) {
                    writer.writeNull();
                } else {
                    codec.encode(writer, entry.getValue(), encoderContext);
                }
            }
            writer.writeEndDocument();
        }

        @Override
        public Map<K, V> decode(final BsonReader reader, final DecoderContext context) {
            reader.readStartDocument();
            Map<K, V> map = getInstance();
            while (reader.readBsonType() != BsonType.END_OF_DOCUMENT) {
                final K key = (K) Conversions.convert(reader.readName(), keyType);
                if (reader.getCurrentBsonType() == BsonType.NULL) {
                    map.put(key, null);
                    reader.readNull();
                } else {
                    map.put(key, codec.decode(reader, context));
                }
            }
            reader.readEndDocument();
            return map;
        }

        @Override
        public Class<Map<K, V>> getEncoderClass() {
            return encoderClass;
        }

        private Map<K, V> getInstance() {
            if (encoderClass.isInterface()) {
                return new HashMap<>();
            }
            try {
                final Constructor<Map<K, V>> constructor = encoderClass.getDeclaredConstructor();
                constructor.setAccessible(true);
                return constructor.newInstance();
            } catch (final Exception e) {
                throw new CodecConfigurationException(e.getMessage(), e);
            }
        }
    }

}


text:
namespace CoreServices
{
    /// <summary>
    /// Provides methods for interacting with core services.
    /// </summary>
    public interface ICoreService
    {
        /// <summary>
        /// This method canonicalises and signs a request, sending and then validating the response.
        /// </summary>
        /// <param name="api">The core service api endpoint to use.</param>
        /// <param name="args">An array of arguments to be appended to the url.</param>
        /// <param name="data">An array of named keywords and their values separated by an equals sign. Example: success=http://successurl.com.</param>
        /// <returns>Returns a string containing the response or an empty string on failure.</returns>
        string Request(string api, string[] args, string[] data);
    }
}


text:
# -*- coding: utf-8 -*-
# Copyright 2017 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""Various URI related helpers."""

from __future__ import print_function

import os
import re
import sys

from six.moves import urllib

assert sys.version_info >= (3, 6), 'This module requires Python 3.6+'

def _ExtractGobClAndSubpath(o):
  """Return a (CL, subpath) tuple if found in the URI parts, or None if not.

  Many forms are supported below.
  """
  path = o.path
  fragment = o.fragment

  # https://chromium-review.googlesource.com/#/662618
  # https://chromium-review.googlesource.com/#/662618/
  # https://chromium-review.googlesource.com/#/662618/////
  if path == '/':
    m = re.match(r'^/(?:c/)?([0-9]+)/*$', fragment)
    if m:
      return (m.group(1), '')

    # Any valid /c/ URI can also be in the fragment.
    if fragment.startswith('/c/'):
      # https://chrome-internal-review.googlesource.com/#/c/280497
      # https://chrome-internal-review.googlesource.com/#/c/280497/
      path = fragment
      fragment = ''
    else:
      return None

  # https://chromium-review.googlesource.com/662618
  # https://chromium-review.googlesource.com/662618/
  m = re.match(r'^/([0-9]+)/?$', path)
  if m:
    return (m.group(1), fragment)

  # https://chromium-review.googlesource.com/c/662618
  # https://chromium-review.googlesource.com/c/662618/
  # https://chromium-review.googlesource.com/c/662618/1/lib/gs.py
  m = re.match(r'^/c/([0-9]+)(/.*)?$', path)
  if m:
    return (m.group(1) + (m.group(2) or '').rstrip('/'), fragment)

  # https://chromium-review.googlesource.com/c/chromiumos/chromite/+/662618
  # https://chromium-review.googlesource.com/c/chromiumos/chromite/+/662618/
  # https://chromium-review.googlesource.com/c/chromiumos/chromite/+/662618/1/lib/gs.py
  m = re.match(r'^/c/.*/\+/([0-9]+)(/.*)?$', path)
  if m:
    return (m.group(1) + (m.group(2) or '').rstrip('/'), fragment)

  return None

def _ShortenGob(o):
  """Shorten a Gerrit-on-Borg URI.

  Args:
    o: The named tuple from a urllib.parse.urlsplit call.

  Returns:
    A new named tuple that can be passed to urllib.parse.urlunsplit.
  """
  parts = _ExtractGobClAndSubpath(o)
  if parts is None:
    return o

  # If we're using a Chromium GoB, use crrev.com.  Otherwise, we'll just
  # shorten the path but keep the original GoB host.
  if o.netloc.split('.')[0] in ('chromium-review', 'chrome-internal-review'):
    netloc = 'crrev.com'
    if o.netloc.startswith('chrome-internal'):
      sub = 'i'
    else:
      sub = 'c'
    path = '/%s/%s' % (sub, parts[0])
  else:
    netloc = o.netloc
    path = '/%s' % (parts[0],)

  return o._replace(scheme='https', netloc=netloc, path=path, fragment=parts[1])

def _ShortenCrosReview(o):
  """Shorten old review to new review hosts.

  Args:
    o: The named tuple from a urllib.parse.urlsplit call.

  Returns:
    A new named tuple that can be passed to urllib.parse.urlunsplit.
  """
  m = re.match(r'^/(i/)?([0-9]+)', o.path)
  if m:
    subpart = 'i' if m.group(1) else 'c'
    o = o._replace(netloc='crrev.com',
                   path='/%s/%s' % (subpart, m.group(2)))

  return o._replace(scheme='https')

def _ShortenRietveld(o):
  """Shorten a rietveld URI.

  Args:
    o: The named tuple from a urllib.parse.urlsplit call.

  Returns:
    A new named tuple that can be passed to urllib.parse.urlunsplit.
  """
  m = re.match(r'^/([0-9]+)', o.path)
  if m:
    o = o._replace(netloc='crrev.com',
                   path='/%s' % (m.group(1),))

  return o._replace(scheme='https')

def _ShortenBuganizer(o):
  """Shorten a buganizer URI.

  Args:
    o: The named tuple from a urllib.parse.urlsplit call.

  Returns:
    A new named tuple that can be passed to urllib.parse.urlunsplit.
  """
  if o.path == '/issue':
    # http://b.corp.google.com/issue?id=123
    qs = urllib.parse.parse_qs(o.query)
    if 'id' in qs:
      o = o._replace(path='/%s' % (qs['id'][0],), query='')
  elif o.path.startswith('/issues/'):
    # http://b.corp.google.com/issues/123
    o = o._replace(path=o.path[len('/issues'):])

  return o._replace(scheme='http', netloc='b')

def _ShortenChromiumBug(o):
  """Shorten a Chromium bug URI.

  Args:
    o: The named tuple from a urllib.parse.urlsplit call.

  Returns:
    A new named tuple that can be passed to urllib.parse.urlunsplit.
  """
  # https://bugs.chromium.org/p/chromium/issues/detail?id=123
  # https://bugs.chromium.org/p/google-breakpad/issues/list
  # These we don't actually shorten:
  # https://bugs.chromium.org/p/chromium/people
  m = re.match(r'/p/([^/]+)/issues(/detail)?', o.path)
  if m is None:
    return o

  if m.group(1) == 'chromium':
    path = ''
  else:
    path = '/%s' % (m.group(1),)

  if m.group(2):
    qs = urllib.parse.parse_qs(o.query)
    if 'id' in qs:
      path += '/%s' % (qs['id'][0],)
    o = o._replace(query='')

  return o._replace(scheme='https', netloc='crbug.com', path=path)

def _ShortenGutsTicket(o):
  """Shorten a Google GUTS ticket URI.

  Args:
    o: The named tuple from a urllib.parse.urlsplit call.

  Returns:
    A new named tuple that can be passed to urllib.parse.urlunsplit.
  """
  # https://gutsv3.corp.google.com/#ticket/123
  m = re.match(r'^ticket/([0-9]+)', o.fragment)
  if m:
    o = o._replace(path='/%s' % (m.group(1),), fragment='')

  return o._replace(scheme='http', netloc='t')

# Map sites to the shortener.  Use a tuple to keep rule ordering sane (even if
# we don't have rules atm relying on it).
_SHORTENERS = (
    (re.compile(r'^[a-z0-9-]+-review\.googlesource\.com$'), _ShortenGob),
    (re.compile(r'^crosreview\.com$'), _ShortenCrosReview),
    (re.compile(r'^codereview\.chromium\.org$'), _ShortenRietveld),
    (re.compile(r'^b\.corp\.google\.com$'), _ShortenBuganizer),
    (re.compile(r'^bugs\.chromium\.org$'), _ShortenChromiumBug),
    (re.compile(r'^gutsv\d\.corp\.google\.com$'), _ShortenGutsTicket),
)

def ShortenUri(uri, omit_scheme=False):
  """Attempt to shorten a URI for humans.

  If the URI can't be shortened, then we just return the original value.
  Thus this can be safely used as a pass-through for anything.

  Args:
    uri: Any valid URI.
    omit_scheme: Whether to include the scheme (e.g. http:// or https://).

  Returns:
    A (hopefully shorter) URI pointing to the same resource as |uri|.
  """
  o = urllib.parse.urlsplit(uri)

  # If the scheme & host are empty, assume it's because the URI we were given
  # lacked a http:// or https:// prefix, so blindly insert a http://.
  if not o.scheme and not o.netloc:
    o = urllib.parse.urlsplit('http://%s' % (uri,))

  for matcher, shortener in _SHORTENERS:
    if matcher.match(o.netloc):
      o = shortener(o)
      break
  else:
    return uri

  if omit_scheme:
    o = o._replace(scheme='')
    # Strip off the leading // due to blank scheme.
    return urllib.parse.urlunsplit(o)[2:]
  else:
    return urllib.parse.urlunsplit(o)

_LUCI_MILO_BUILDBOT_URL = 'https://luci-milo.appspot.com/buildbot'

_LOGDOG_URL = ('https://luci-logdog.appspot.com/v/'
               '?s=chromeos/buildbucket/cr-buildbucket.appspot.com/'
               '%s/%%2B/steps/%s/0/stdout')

# Will redirect:
#   https://ci.chromium.org/b/8914470887449121184
# to:
#   https://ci.chromium.org/p/chromeos/builds/b8914470887449121184
_MILO_BUILD_URL = 'https://ci.chromium.org/b/%(buildbucket_id)s'

def ConstructMiloBuildUri(buildbucket_id):
  """Return a Milo build URL.

  Args:
    buildbucket_id: Buildbucket id of the build to link.

  Returns:
    The fully formed URI.
  """
  # Only local tryjobs will not have a buildbucket_id but they also do not have
  # a web UI to point at. Generate a fake URL.
  buildbucket_id = buildbucket_id or 'fake_bb_id'
  return _MILO_BUILD_URL % {'buildbucket_id': buildbucket_id}

def ConstructDashboardUri(buildbot_master_name, builder_name, build_number):
  """Return the dashboard (luci-milo) URL for this run

  Args:
    buildbot_master_name: Name of buildbot master, e.g. chromeos
    builder_name: Builder name on buildbot dashboard.
    build_number: Build number for this validation attempt.

  Returns:
    The fully formed URI.
  """
  url_suffix = '%s/%s' % (builder_name, str(build_number))
  url_suffix = urllib.parse.quote(url_suffix)
  return os.path.join(
      _LUCI_MILO_BUILDBOT_URL, buildbot_master_name, url_suffix)

def ConstructLogDogUri(build_number, stage):
  """Return the logdog URL for the given build number and stage.

  Args:
    build_number: The build ID.
    stage: The name of the stage to view logs for.

  Returns:
    The fully formed URI.
  """
  return _LOGDOG_URL % (str(build_number), stage)

def ConstructViceroyBuildDetailsUri(build_id):
  """Return the dashboard (viceroy) URL for this run.

  Args:
    build_id: CIDB id for the master build.

  Returns:
    The fully formed URI.
  """
  _link = ('https://viceroy.corp.google.com/'
           'chromeos/build_details?build_id=%(build_id)s')
  return _link % {'build_id': build_id}

def ConstructGoldenEyeBuildDetailsUri(build_id):
  """Return the dashboard (goldeneye) URL for this run.

  Args:
    build_id: CIDB id for the build.

  Returns:
    The fully formed URI.
  """
  _link = ('http://go/goldeneye/'
           'chromeos/healthmonitoring/buildDetails?id=%(build_id)s')
  return _link % {'build_id': build_id}


text:
var async = require('async');
var chai = require('chai');
var assert = chai.assert;
var fs = require('fs-extra');
var path = require('path');
var temp = require('temp');
var c2l = require('../index');

temp.track();

describe('copyExistingFiles', function () {
    it('should work on export0', function (done) {
        temp.mkdir('export0-shouldwork', function (err, dirPath) {
            if (err) return done(err);
            c2l.copyExistingFiles('test/files/export0', dirPath, function (err) {
                if (err) return done(err);
                fs.readdir(dirPath, function (err, files) {
                    async.each(files, function (file, callback) {
                        fs.stat(path.join(dirPath, file), function (err, stats) {
                            // Assert file exists
                            assert.isNull(err);
                            callback();
                        });
                    }, function (err) { done(err); });
                });
            });
        });
    });
});

describe('generateHtml', function () {
    it('should work on export0', function (done) {
        temp.mkdir('export0-shouldwork', function (err, dirPath) {
            if (err) return done(err);
            var src = 'test/files/export0';
            fs.readFile(path.join(src, 'viz.json'), function (err, data) {
                if (err) {
                    callback(err);
                    return;
                }
                var visJson = JSON.parse(data);
                c2l.generateHtml(visJson, src, dirPath, function (err) {
                    if (err) return done(err);
                    fs.stat(path.join(dirPath, 'index.html'), function (err, stats) {
                        // Assert file exists
                        assert.isNull(err);
                        done();
                    });
                });
            });
        });
    });
});

describe('generateJavaScript', function () {
    it('should work on export0', function (done) {
        temp.mkdir('export0-shouldwork', function (err, dirPath) {
            if (err) return done(err);
            var src = 'test/files/export0';
            fs.readFile(path.join(src, 'viz.json'), function (err, data) {
                if (err) {
                    callback(err);
                    return;
                }
                var visJson = JSON.parse(data);
                c2l.generateJavaScript(visJson, src, dirPath, function (err) {
                    if (err) return done(err);
                    fs.stat(path.join(dirPath, 'cartodb2leaflet.js'), function (err, stats) {
                        // Assert file exists
                        assert.isNull(err);
                        done();
                    });
                });
            });
        });
    });
});

describe('generateStyles', function () {
    it('should call callback on export0', function (done) {
        temp.mkdir('export0-shouldwork', function (err, dirPath) {
            if (err) return done(err);
            var src = 'test/files/export0';
            fs.readFile(path.join(src, 'viz.json'), function (err, data) {
                if (err) {
                    return done(err);
                }
                var visJson = JSON.parse(data);
                c2l.generateStyles(visJson, src, dirPath, function (err) {
                    if (err) return done(err);
                    done();
                });
            });
        });
    });
});

describe('generateFiles', function () {
    it('should call callback on export0', function (done) {
        temp.mkdir('export0-shouldwork', function (err, dirPath) {
            if (err) return done(err);
            var src = 'test/files/export0';
            c2l.generateFiles(src, dirPath, function (err) {
                if (err) return done(err);
                done();
            });
        });
    });
});

describe('toLeaflet', function () {
    it('should call callback on export0', function (done) {
        temp.mkdir('export0-shouldwork', function (err, dirPath) {
            if (err) return done(err);
            var src = 'test/files/export0';
            c2l.toLeaflet(src, dirPath, function (err) {
                if (err) return done(err);
                done();
            });
        });
    });
});


text:
from xml.dom.minidom import parse
from xml.dom.minidom import Node
import bpy

def createmeshfac(filename):
    meshfac = parse(filename)

    verts = meshfac.getElementsByTagName("v")
    varr = [[0]*3]*verts.length
    vi = 0
    for i in verts:
        tv = [0]*3
        x = i.getAttribute("x")
        y = i.getAttribute("y")
        z = i.getAttribute("z")
        tv[0] = float(x)
        tv[2] = float(y)
        tv[1] = float(z)
        varr[vi] = tv
        vi = vi +1

    ts = meshfac.getElementsByTagName("t")
    tarr = [[0]*3]*ts.length
    ti = 0
    for it in ts:
        tt=[0]*3
        v1 = it.getAttribute("v1")
        v2 = it.getAttribute("v2")
        v3 = it.getAttribute("v3")
        tt[0] = int(v1)
        tt[1] = int(v2)
        tt[2] = int(v3)
        tarr[ti] = tt
        ti = ti +1

    submeshsn = meshfac.getElementsByTagName("submesh")
    matname = "defined"
    if submeshsn.length == 0 :
        matname = meshfac.getElementsByTagName("material")[0].childNodes[0].data
    return [varr,tarr,matname]

def create_mesh_object(context, verts, edges, faces, name):
    # Create new mesh
    mesh = bpy.data.meshes.new(name)
    # Make a mesh from a list of verts/edges/faces.
    mesh.from_pydata(verts, edges, faces)
    # Update mesh geometry after adding stuff.
    mesh.update()
    from bpy_extras import object_utils
    return object_utils.object_data_add(context, mesh, operator=None)

def check_mat(matname):
    for im in bpy.data.materials :
        if im.name == matname :
            return im

    return False

worldxml = parse("E:\\treew\\art\\world.xml")
meshobjs = worldxml.getElementsByTagName("meshobj")
for obj in meshobjs:
    objname  = obj.getAttribute("name")
    print(objname + "\n")
    mvnode = obj.getElementsByTagName("v")
    mx = mvnode[0].getAttribute("x")
    my = mvnode[0].getAttribute("z")
    mz = mvnode[0].getAttribute("y")
    move = [float(mx),float(my),float(mz)]
    # print(move)
    rotx =  obj.getElementsByTagName("rotx")
    roty =  obj.getElementsByTagName("rotz")
    rotz =  obj.getElementsByTagName("roty")
    rx = rotx[0].childNodes[0].data
    ry = roty[0].childNodes[0].data
    rz = rotz[0].childNodes[0].data
    rot = [-float(rx),-float(ry),-float(rz)]
    # print(rot)
    iscale = obj.getElementsByTagName("scale")
    sx = iscale[0].getAttribute("x")
    sy = iscale[0].getAttribute("z")
    sz = iscale[0].getAttribute("y")
    scale = [1/float(sx),1/float(sy),1/float(sz)]
    fac = obj.getElementsByTagName("factory")
    facname = fac[0].childNodes[0].data
    factory = createmeshfac("E:\\treew\\art\\factories\\" + facname + ".xml")
    tmpmesh = create_mesh_object(bpy.context,factory[0],[],factory[1],objname)
    bpy.context.active_object.location.xyz = move
    bpy.context.active_object.rotation_euler = rot
    bpy.context.active_object.scale.xyz = scale

    mat = check_mat(factory[2])
    if mat == False:
        mat =  bpy.data.materials.new(factory[2])

    bpy.context.active_object.data.materials.append(mat)


text:
package org.jivesoftware.smackx.jingle.listeners;

import org.jivesoftware.smackx.jingle.JingleSessionRequest;

/**
 * Interface to listener Jingle session requests.
 *
 * @author Alvaro Saurin
 */
public interface JingleSessionRequestListener extends JingleListener {
    /**
     * A request to start a session has been recieved from another user.
     *
     * @param request The request from the other user.
     */
    public void sessionRequested(JingleSessionRequest request);
}


text:
layout: post
title: Internet je čudo
date: '2006-05-11 08:44:47 +0200'
mt_id: 171
post_id: 171
author: jablan
---
Pre par dana od dobrog drugara dobijem SMS sledeće sadržine: _"Internet je chudo! L. (moj chale) se zeni. Upoznao neku zenu na Krstarici"_

Dakle, prethodno informatički nepismen čovek, običan radnik od svojih pedesetak godina nabavio komp, naučio osnovne stvari i upoznao srodnu dušu na netu. :) Tako da: sledeći put kad vam se neko bude žalio što će, avaj, izgubiti posao u privatizovanoj firmi jer ne poznaje "rad na računaru", a, bože moj, "gde će da uči nešto u ovim godinama", uzmite ovaj URL pa mu natrljajte nos.

Sajber-mladencima želim sve najbolje u budućem suživotu: ovim potvrđuju da je mladost (starost) subjektivna kategorija i da Srbija ipak ponekad zaliči na normalnu zemlju.


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>Mesh face material</title>
    <meta name="description" content="">
    <meta name="keywords" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0">


text:
"use strict";

const chai = require('chai');
const expect = chai.expect;

// 1 green: hard-code the correct answer

function timeString(string) {
	return '0:00:01';
}

describe('timeString test', function() {

  it('Returns single output when string is inputed', function() {
    expect(timeString('00:01')).to.equal('0:00:01');
  });

});