text:
<?xml version="1.0" encoding="utf-8"?>
<layout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <data>

        <import type="zlc.season.rxdownloadproject.model.BaseModel"/>

        <variable
            name="item"
            type="BaseModel"/>
    </data>

    <android.support.design.widget.CoordinatorLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true"
        tools:context="zlc.season.rxdownloadproject.activity.BasicDownloadActivity">

        <android.support.design.widget.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:theme="@style/AppTheme.AppBarOverlay">

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                app:title="@string/title_activity_basic_download"
                android:background="?attr/colorPrimary"
                app:popupTheme="@style/AppTheme.PopupOverlay"/>

        </android.support.design.widget.AppBarLayout>

        <include
            android:id="@+id/content_basic_download"
            layout="@layout/content_basic_download"
            app:item="@{item}"/>

        <android.support.design.widget.FloatingActionButton
            android:id="@+id/fab"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom|end"
            android:layout_margin="@dimen/fab_margin"
            app:srcCompat="@android:drawable/ic_dialog_email"/>

    </android.support.design.widget.CoordinatorLayout>
</layout>


text:
title: OnBatchEditGetCellValue
page_title: OnBatchEditGetCellValue | RadGrid for ASP.NET AJAX Documentation
description: OnBatchEditGetCellValue
slug: grid/client-side-programming/events/onbatcheditgetcellvalue
tags: onbatcheditgetcellvalue
published: True
position: 79
---

# OnBatchEditGetCellValue

##

OnBatchEditGetCellValue

This event should be handled when multiple controls which contain an input element are placed inside the EditItemTemplate of a GridTemplateColumn. It should be used for extracting the value from the cell and passing it to the arguments. Later this value is used for populating the editor.

|  **Fired by**  | RadGrid |
| ------ | ------ |
| **Arguments** | **container** - gets the container of the edited cell **cell** - gets the currently edited cell **row** - gets the currently edited row **column** - gets the currently edited column **columnUniqueName** - gets the UniqueName of the edited column **tableView** - gets the TableView in which the edited item is located **value** - gets the cell value **cancel** - returns a value indicating whether the event is canceled|
| **Can be canceled** |Yes, set args.set_cancel(true) to cancel|

Example:

````ASP.NET
function BatchEditGetCellValue(sender, args) {
    var itemContainer = args.get_container();
    var cell = args.get_cell();
    var row = args.get_row();
    var column = args.get_column();
    var columnUniqueName = args.get_columnUniqueName();
    var currentlyEditedTable = args.get_tableView();
    var cellValue = args.get_value();
    var isEventCanceled = args.get_cancel();
}
````

````JavaScript
<telerik:RadGrid ID="RadGrid1" DataSourceID="SqlDataSource1">
    <MasterTableView EditMode="Batch">
    <ClientSettings>
        <ClientEvents OnBatchEditGetCellValue="BatchEditGetCellValue"/>
    </ClientSettings>
</telerik:RadGrid>
````

redpajama_set_name: RedPajamaGithub


text:
package com.wh.base.web.action.privilege;

import java.io.File;
import java.util.UUID;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.wh.base.bean.privilege.User;
import com.wh.base.service.user.UserService;
import com.wh.base.utils.FileUtil;
import com.wh.base.utils.SiteUrl;
@Controller
public class EditUserAction extends ActionSupport {
	private static final long serialVersionUID = 1L;
	@Resource
	private UserService userService;
	private File picture;
	private String pictureFileName;
	private String pictureContentType;
	private String username;
	private String realname;
	private String password;
	@Override
	public String execute() throws Exception {
		String message = "修改成功";
		String ext = FileUtil.getExt(pictureFileName);
		if(!FileUtil.validateImageFileType(pictureContentType, ext)) {
			message = "文件格式不正确,只允许上传gif/jpg/png/bmp图片";
		} else {
			//构建文件名称
			String fileName = UUID.randomUUID().toString()+ "."+ext;
			FileUtil.saveImageFile(picture, fileName, username);
			User user = userService.find(username);
			user.setPassword(password);
			user.setRealname(realname);
			user.setPicture(fileName);
			userService.update(user);
		}
		System.out.println("临时文件路径:" + picture.getAbsolutePath());
		ActionContext.getContext().put("message", message);
		ActionContext.getContext().put("urladdress", SiteUrl.readUrl("user.list"));
		return "message";
	}
	public File getPicture() {
		return picture;
	}
	public void setPicture(File picture) {
		this.picture = picture;
	}
	public String getPictureFileName() {
		return pictureFileName;
	}
	public void setPictureFileName(String pictureFileName) {
		this.pictureFileName = pictureFileName;
	}
	public String getPictureContentType() {
		return pictureContentType;
	}
	public void setPictureContentType(String pictureContentType) {
		this.pictureContentType = pictureContentType;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getRealname() {
		return realname;
	}
	public void setRealname(String realname) {
		this.realname = realname;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
}


text:
> Durum Senaryomuz : C# ile yazdığımız bir projede, PayU ödeme sistemini kullanıyoruz. İhtiyacımız ise PayU'nun bizlere sağlamış olduğu v1 kredi kartı sorgulama api'sini kullanmak ve kartın sadece ilk 6 hanesi(BIN) ile; kart tipi, hangi bankaya ait olduğu, taksit vb bir çok bilgiyi çekmek.
## Card Info - API v1
Card Info - API v1 ile bize olası dönebilecek bilgiler:

- "binType":"VISA"
- "binIssuer":"IS BANK",
- "cardType":"CREDIT",
- "country":"Turkey",
- "program":"Maximum",
- "installments":[1,"2","3","4","5","6","7","8","9","10","11","12"],
- "paymentMethod":"CCVISAMC"

binType: VISA, MasterCard vb olarak kartın tipini öğrenebilir, ilgili sayfanızda hazırlayacağınız temsili bir kart ile de logosunu gösterebilirsiniz. Ayrıca kartın ilk 6 hanenin girilmesini beklemeden de kartın ilk iki hanesi ve küçük bir liste ile aynı kontrolü sağlayabilirsiniz.

binIssuer / program / installments Bu alanlar ise çalışmamızda ihtiyacımız olan en önemli alanlar. Bunun en büyük sebebi PayU'nun taksit oranlarınızı içeren bir servis paylaşmıyor oluşu ve aynı tabloyu kendi sisteminizde tekrar hazırmanızı istemesi:

Ayrıca bir yanlış anlaşılmaya izin vermemek için değinmeliyim, eğer v2 kullanırsanız karta ait taksit komisyonlarını çekebiliyorsunuz ancak burada ki asıl sorun, bizden karta ait tüm bilgileri istemesi.

En nihayetinde ilgili ürüne ait sayfada, tüm kartların taksit oranlarını paylaşmak istiyorsak.. Kendi tablomuzu oluşturmak zorundayız.

## Neden v2 değil de v1 kullanıyoruz ?

Her ne kadar v2 ile girilen kartın taksit komisyonlarına ulaşabiliyor olsak da bunun için karta ait tüm bilgileri girmemiz istenmekte. Bizim tek amacımız çalışan bir sistem ise tercih edilebilir gözükmekte ancak doğru çalışan bir sistem ise, durup düşünmekte fayda var! Zira yapılan araştırmalarda sepeti terketme oranlarını hiç %60 altında görmedim. Hal böyleyken kullanıcıya tüm kart bilgilerini girdikten sonra taksit bilgilerini sunmak, bir çok sabırsız müşteriyi kaybetmek olacaktır.

Bizlerin amacı ise v1 ile gerekli bilgileri elde etmek, daha sonra bunu kendi taksit tablomuz ile karşılaştırarak ilgili oranları daha ilk altı hanede sunmuş olmak.

## Başlayalım!

Elimizde Http ile haberleşeceğimiz bir servis bulunmakta. İstekte bulunacağımız bu yapıyı inceleyelim:

Dökümanlarında yer alan örnek yapı

> https://secure.payu.com.tr/api/card-info/v1/ (İstekte bulunacağımız servisimiz.)
- 4444444444 (Kartımızın en az ilk altı hanesi.)
- ?timestamp=1421426073 (Unix zaman damgamız)
- &merchant=MERCHANTCODE (PayU tarafından size özel sağlanan kodunuz.)
- &signature=8ab027fdaf1eee0e1ecf2dd82cabc9a6668420011d05a1de329782b5b2566c57 (Yine PayU tarafından sizlere sağlanan gizli kodunuz ile oluşturabileceğiniz imzanız.)

#### Adım adım isteğimizi oluşturalım.

1. Kartın ilk 6 hanesini yakalayıp controller'a değerimizi gönderiyoruz :

```html

    <div style="width:600px; margin:60px auto; text-align:center;" >
        <h1>PayU Card Info v1</h1>
        <h5>- CARD NO -</h5>

        <input id="CardBIN" type="number"/>

        <div style="margin: 40px auto; border: 1px solid; border-radius: 36px; height: 245px; width: 400px; font-size: 1.3em;">
            <div id="binType" style="float: right; padding: 20px 28px;"></div>
            <div id="country" style="float: left; padding: 20px 28px;"></div>
            <div id="cardno" style="margin-top: 100px; font-size: 1.6em;"></div>
            <div id="binIssuer" style="float: left; padding: 48px 20px;"></div>
            <div id="program" style="float: right; padding: 48px 20px;"></div>
        </div>
      </div>

```
```javascript
$('#CardBIN').on('keyup change', function () {

                $("#cardno").html($(this).val().replace(/\W/gi, '').replace(/(.{4})/g, '$1 '))

                if ($(this).val().length === 6) {
                    var data = { _CardNum: $(this).val() }
                    $.ajax({
                        url: "fGetPayuCardBINV1",
                        type: "POST",
                        data: JSON.stringify(data),
                        contentType: "application/json; charset=utf-8",
                        datatype: "json",
                        success: function (data)
                        {
                            $("#binType").html(data._BinData.root.cardBinInfo.binType);
                            $("#country").html(data._BinData.root.cardBinInfo.country);
                            $("#binIssuer").html(data._BinData.root.cardBinInfo.binIssuer);
                            $("#program").html(data._BinData.root.cardBinInfo.program);
                        }
                    });
                }
            });
```
Bu alanda açıklayacak pek bir şey yok diye düşünüyorum... Ajax ile değerimizi gönderiyor, dönen sonucumuzu ise ilgili alanlara basıyoruz.

2. timestamp

Bunun için isteğin gerçekleştiği zamanı gerekli formata çevirmemiz gerekmekte :

```c#
public long ConvertToUnixTime(DateTime datetime)
        {
            DateTime sTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

            return (long)(datetime - sTime).TotalSeconds;

        }
```

3. merchant

PayU tarafından sizlere özel sağlanan kodunuz.

4. signature

Bu alanda istek imzamızı oluşturuyoruz. Belirli verilerimiz ile oluşturduğumuz imzamızı, PayU'nun bize özel verdiği gizli kodu kullanarak SHA256 ile kriptoluyoruz. Gizli kodu merchant ile karıştırmayın.

```c#

   public byte[] hmacSHA256(String data, String key)
        {
            using (HMACSHA256 hmac = new HMACSHA256(Encoding.ASCII.GetBytes(key)))
            {
                return hmac.ComputeHash(Encoding.ASCII.GetBytes(data));
            }
        }

```

5. Sonuç (Http Request)

```c#

        public JsonResult fGetPayuCardBINV1(string _CardNum)
        {
            /// Http Request için kullanacağımız metodumuz.
            WebClient _Client = new WebClient();
            /// Dönen sonucumuzu basacağımız class yapımız.
            BINDataResponseV1 _BinData = new BINDataResponseV1();

            /// İstekte bulunacağımız servisimiz
            string URL = "https://secure.payu.com.tr/api/card-info/v1/";
            /// PayU tarafından size özel sağlanan kodunuz.
            string merchant = "";
            /// PayU tarafından size özel sağlanan gizli kodunuz.
            string secretkey = "";
            /// Unix zaman damgamız
            string timestamp = ConvertToUnixTime(DateTime.Now.AddHours(-3)).ToString();
            /// PayU tarafından sizlere sağlanan gizli kodunuz ile oluşturacağınız imzanız.
            string signature = BitConverter.ToString(hmacSHA256(merchant + timestamp, secretkey)).Replace("-", "").ToLower();

            /// Http Request işleminiz.
            var _Request = _Client.DownloadString(URL + _CardNum + "?merchant=" + merchant + "&timestamp=" + timestamp + "&signature=" + signature);
            /// Sonuç
            _BinData.root = JsonConvert.DeserializeObject<BINDataResponseV1.ROOT>(_Request);

            return Json(new { _BinData = _BinData }, JsonRequestBehavior.AllowGet);

        }

```


text:
ActiveRecord::Schema.define(version: 20140826215844) do

  create_table "admin_resources", force: true do |t|
    t.integer  "res_seq"
    t.string   "res_id"
    t.string   "res_desc"
    t.string   "res_controller"
    t.string   "res_action"
    t.string   "status"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "admin_roles", force: true do |t|
    t.string   "role_name"
    t.string   "role_desc"
    t.string   "status"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "admin_users", force: true do |t|
    t.string   "user_name"
    t.string   "user_id"
    t.string   "password_digest"
    t.string   "session_token"
    t.string   "salt"
    t.string   "status"
    t.string   "auth_request_time"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  add_index "admin_users", ["password_digest"], name: "index_admin_users_on_password_digest"
  add_index "admin_users", ["session_token"], name: "index_admin_users_on_session_token"
  add_index "admin_users", ["user_id"], name: "index_admin_users_on_user_id", unique: true

  create_table "roles_resources", force: true do |t|
    t.integer  "role_id"
    t.integer  "resource_id"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  add_index "roles_resources", ["resource_id"], name: "index_roles_resources_on_resource_id"
  add_index "roles_resources", ["role_id"], name: "index_roles_resources_on_role_id"

  create_table "users_roles", force: true do |t|
    t.integer  "user_id"
    t.integer  "role_id"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  add_index "users_roles", ["role_id"], name: "index_users_roles_on_role_id"
  add_index "users_roles", ["user_id"], name: "index_users_roles_on_user_id"

end


text:
<ui:UiBinder xmlns:ui='urn:ui:com.google.gwt.uibinder'
	xmlns:g='urn:import:com.google.gwt.user.client.ui' ui:generateFormat='com.google.gwt.i18n.rebind.format.PropertiesFormat'
	ui:generateKeys="com.google.gwt.i18n.rebind.keygen.MD5KeyGenerator"
	ui:generateLocales="default">
	<g:HTMLPanel ui:field="contentPanel">

								<g:Anchor ui:field="showList">

										<ui:msg key="list">List</ui:msg>

								</g:Anchor>

			<g:HTMLPanel ui:field="mapPanel" height="555" width="629"
				styleName="inner_listing">
			</g:HTMLPanel>

								<g:ListBox ui:field="sortTypesList" styleName="text_field8" />

				<g:HTMLPanel ui:field="searchPanel" styleName="gray_bg">
				</g:HTMLPanel>

					<g:ListBox ui:field="pTypesList" styleName="text_field9" />
					<g:ListBox ui:field="priceTypesList" styleName="text_field8" />
					<g:ListBox ui:field="sftTypesList" styleName="text_field10" />

				<g:HTMLPanel ui:field="propertiesGridPanel" styleName="listing_txt">
				</g:HTMLPanel>
				<g:HTMLPanel ui:field="paging">
				</g:HTMLPanel>

	</g:HTMLPanel>
</ui:UiBinder>


text:
use core::pin::Pin;
use futures_core::future::Future;
use futures_core::task::{Context, Poll};

/// A macro which yields to the event loop once.
///
/// This is equivalent to returning [`Poll::Pending`](futures_core::task::Poll)
/// from a [`Future::poll`](futures_core::future::Future::poll) implementation.
/// Similarly, when using this macro, it must be ensured that [`wake`](std::task::Waker::wake)
/// is called somewhere when further progress can be made.
///
/// This macro is only usable inside of async functions, closures, and blocks.
/// It is also gated behind the `async-await` feature of this library, which is
/// activated by default.
#[macro_export]
macro_rules! pending {
    () => {
        $crate::__private::async_await::pending_once().await
    };
}

#[doc(hidden)]
pub fn pending_once() -> PendingOnce {
    PendingOnce { is_ready: false }
}

#[allow(missing_debug_implementations)]
#[doc(hidden)]
pub struct PendingOnce {
    is_ready: bool,
}

impl Future for PendingOnce {
    type Output = ();
    fn poll(mut self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Self::Output> {
        if self.is_ready {
            Poll::Ready(())
        } else {
            self.is_ready = true;
            Poll::Pending
        }
    }
}


text:
import { StorageChannel } from './channel';
import { storageEventStream$ } from '../../../infrastructure/webstorage/api';

describe('Unit: layers/domain/webstorage/service/channel', () => {
  describe('spec', () => {
    interface DAO extends StorageChannel.Value {
    }
    class DAO {
      value = 0;
    }

    beforeEach(() => {
      sessionStorage.removeItem('test');
    });

    it('resource', () => {
      const chan = new StorageChannel('test', sessionStorage, { schema: () => new DAO() });
      assert.throws(() => new StorageChannel('test', sessionStorage, { schema: () => new DAO() }));
      chan.destroy();
    });

    it('make/destroy', () => {
      assert(sessionStorage.getItem('test') === null);
      const chan = new StorageChannel('test', sessionStorage, { schema: () => new DAO() });
      const link = chan.link();
      assert(link.value === 0);
      assert(sessionStorage.getItem('test') === null);
      link.value = 1;
      assert(link.value === 1);
      assert(sessionStorage.getItem('test') === '{\"value\":1}');
      assert(chan.unlink(link) === true);
      link.value = 2;
      assert(chan.unlink(link) === false);
      assert(link.value === 2);
      assert(sessionStorage.getItem('test') === '{\"value\":1}');
      assert(chan.unlink() === false);
      chan.link().value = 3;
      assert(sessionStorage.getItem('test') === '{\"value\":3}');
      assert(chan.unlink(link) === false);
      assert(chan.unlink() === true);
      assert(chan.unlink() === false);

      chan.destroy();
      assert(link.value === 2);
      assert(sessionStorage.getItem('test') === null);
    });

    it('remake', () => {
      assert(sessionStorage.getItem('test') === null);
      const chan = new StorageChannel('test', sessionStorage, { schema: () => new DAO() });
      assert(chan.link() === chan.link());
      chan.destroy();
      new StorageChannel('test', sessionStorage, { schema: () => new DAO() })
        .destroy();
      assert(sessionStorage.getItem('test') === null);
    });

    it('update', () => {
      const chan = new StorageChannel('test', sessionStorage, { schema: () => new DAO() });
      const link = chan.link();
      assert(link.value === 0);
      link.value = 1;
      assert(link.value === 1);
      assert(JSON.parse(sessionStorage.getItem('test')!).value === 1);
      link.value = 0;
      assert(link.value === 0);
      assert(JSON.parse(sessionStorage.getItem('test')!).value === 0);
      chan.destroy();
    });

    it('migrate', () => {
      sessionStorage.setItem('test', JSON.stringify({ value: 0 }));
      const chan = new StorageChannel('test', sessionStorage, {
        schema: () => new DAO(),
        migrate: v => {
          if (v.value % 2) return;
          v.value += 1;
        },
      });
      const link = chan.link();
      assert(link.value === 1);
      assert(JSON.parse(sessionStorage.getItem('test')!).value === 1);
      sessionStorage.setItem('test', JSON.stringify({ value: 2 }));
      storageEventStream$.emit(['session', chan.name], { newValue: '{"value": 2}' } as StorageEvent)
      assert(link.value === 3);
      assert(JSON.parse(sessionStorage.getItem('test')!).value === 3);
      chan.destroy();
    });

  });

});


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:orientation="vertical">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="150dp"
        android:adjustViewBounds="true"
        android:scaleType="centerInside"
        android:src="@drawable/bg_error"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        android:text="加载失败"
        android:textStyle="bold"
        android:textSize="18sp"
        android:textColor="@color/primary_text"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:text="请猛戳CC娘重试"
        android:textSize="14sp"
        android:textColor="@color/secondary_text"/>
</LinearLayout>


text:
Expect no further fixes or features. Anyone is free to fork, modify, and publish the extension, but please do not reuse the name "Saka Key" without permission. There are many maintained alternatives listed at the bottom.

Why: The original developer does not and will not have the time and motivation to continue.

# Saka Key

Saka Key is a Chrome and Firefox extension for keyboard-only web browsing. It's configurable, easy to use, and engineered thoughtfully. Install it from the [Chrome Web Store](https://chrome.google.com/webstore/detail/saka-key/hhhpdkekipnbloiiiiaokibebpdpakdp) or the [Firefox Marketplace](https://addons.mozilla.org/en-US/firefox/addon/saka-key/). Also read the [Saka Key Handbook](https://key.saka.io) and try the accompanying tab search extension [Saka](https://github.com/lusakasa/saka).

![Saka Key Preview](./docs/docs/assets/saka-key-preview.gif)

### Install

Follow the [Development Setup Guide](https://key.saka.io/docs/developers/setup.html) for detailed instructions. Otherwise:

```sh
git clone https://github.com/lusakasa/saka-key.git
cd saka-key
npm install
# Option 1. Chrome development build
npm run start:chrome
# Option 2. Chrome production build
npm run build:chrome
# Option 3. Firefox development build
npm run start:firefox
# Option 4. Firefox production build
npm run build:firefox
```

## Credits

MIT Licensed, Copyright (c) 2018 Sufyan Dawoodjee, Neil Macintyre, Brandon Kalinowski

Saka Key is inspired by and derives from

- [Vimium](https://github.com/philc/vimium)
- [Vimari](https://github.com/guyht/vimari)
- [cVim](https://github.com/1995eaton/chromium-vim)
- [Surfingkeys](https://github.com/brookhong/Surfingkeys)
- [VimFX](https://github.com/akhodakivskiy/VimFx)


text:
import { LocaleCode } from '../../application/locales';
import { LocaleStore } from '../../stores/locale';

export const toSelectorLocale = (store: LocaleStore): LocaleCode => store.code;


text:
<?php

namespace Riak\Client\Core\Transport\Proto\Index;

use ArrayIterator;
use DrSlump\Protobuf\Message;
use Riak\Client\Core\RiakContinuableIterator;
use Riak\Client\Core\Message\Index\IndexEntry;
use Riak\Client\Core\Message\Index\IndexQueryRequest;
use Riak\Client\Core\Transport\Proto\ProtoStreamIterator;
use Riak\Client\Core\Transport\Proto\ProtoStreamIteratorIterator;

/**
 * RPB index query response iterator
 *
 * @author Fabio B. Silva <fabio.bat.silva@gmail.com>
 */
class ProtoIndexQueryResponseIterator extends ProtoStreamIteratorIterator implements RiakContinuableIterator
{
    /**
     * @var \Riak\Client\Core\Message\Index\IndexQueryRequest $request
     */
    private $request;

    /**
     * @param \Riak\Client\Core\Message\Index\IndexQueryRequest     $request
     * @param \Riak\Client\Core\Transport\Proto\ProtoStreamIterator $iterator
     */
    public function __construct(IndexQueryRequest $request, ProtoStreamIterator $iterator)
    {
        $this->request = $request;

        parent::__construct($iterator);
    }

    /**
     * {@inheritdoc}
     */
    public function hasContinuation()
    {
        return $this->message && $this->message->hasContinuation();
    }

    /**
     * {@inheritdoc}
     */
    public function getContinuation()
    {
        if ( ! $this->hasContinuation()) {
            return null;
        }

        return $this->message->continuation;
    }

    /**
     * {@inheritdoc}
     */
    protected function extract(Message $message)
    {
        if ($message->hasResults()) {
            return $this->iteratorFromResults($message->results);
        }

        if ($message->hasKeys()) {
            return $this->iteratorFromKeys($message->keys);
        }

        return null;
    }

    /**
     * @param array $results
     *
     * @return array
     */
    private function iteratorFromResults(array $results)
    {
        $values = [];

        foreach ($results as $pair) {
            $entry = new IndexEntry();

            $entry->indexKey  = $pair->key;
            $entry->objectKey = $pair->value;

            $values[] = $entry;
        }

        return new ArrayIterator($values);
    }

    /**
     * @param array $keys
     *
     * @return array
     */
    private function iteratorFromKeys(array $keys)
    {
        $values = [];
        $key    = ($this->request->qtype === 'eq')
            ? $this->request->key
            : null;

        foreach ($keys as $value) {
            $entry = new IndexEntry();

            $entry->indexKey  = $key;
            $entry->objectKey = $value;

            $values[] = $entry;
        }

        return new ArrayIterator($values);
    }
}


text:
<?php

namespace phpDocumentor\Compiler\Pass;

use phpDocumentor\Compiler\CompilerPassInterface;
use phpDocumentor\Descriptor\ClassDescriptor;
use phpDocumentor\Descriptor\InterfaceDescriptor;
use phpDocumentor\Descriptor\ProjectDescriptor;
use phpDocumentor\Reflection\Fqsen;

final class InterfaceTreeBuilder implements CompilerPassInterface
{
    const COMPILER_PRIORITY = 9000;

    /**
     * Returns a textual description of what this pass does for output purposes.
     *
     * Please note that the command line will be truncated to 68 characters (<message> .. 000.000s) so longer
     * descriptions won't have much use.
     *
     * @return string
     */
    public function getDescription()
    {
        return "Adding Parents to child interfaces";
    }

    /**
     * Executes a compiler pass.
     *
     * This method will execute the business logic associated with a given compiler pass and allow it to manipulate
     * or consumer the Object Graph using the ProjectDescriptor object.
     *
     * @param ProjectDescriptor $project Representation of the Object Graph that can be manipulated.
     *
     * @return mixed
     */
    public function execute(ProjectDescriptor $project)
    {
        foreach ($project->getFiles() as $file) {
            /** @var InterfaceDescriptor $interface */
            foreach ($file->getInterfaces()->getAll() as $interface) {
                foreach ($interface->getParent()->getAll() as $parentName) {
                    $parent = $project->getIndexes()->get('interfaces')->get((string)$parentName);
                    if ($parent instanceof InterfaceDescriptor) {
                        $interface->getParent()->set((string)$parentName, $parent);
                    }
                }
            }
        }
    }
}


text:
import hashlib
import datetime

from django import forms
from django.contrib.localflavor.de.forms import DEZipCodeField

from shoppy.newsletter.models import *

class SubscripeForm(forms.Form):
    name = forms.CharField(max_length=200, required=False)
    email = forms.EmailField(max_length=75, required=True)
    zip = DEZipCodeField(required=False)

    def clean_email(self):
        email = self.cleaned_data['email']
        try:
            subs = Subscriper.objects.get(email=email)
            if subs.isActivated:
                raise forms.ValidationError(
                    unicode('Die Email-Adressen ist schon für den Oláletter registriert.','latin-1'))

            if subs.suspend_until > datetime.datetime.now():
                    raise forms.ValidationError(
                    unicode('Die Email-Adressen ist momentan für den Oláletter gesperrt.','latin-1'))

        except Subscriper.DoesNotExist:
            return email

        return email

    def save(self, request=None, **kwargs):
        data = self.cleaned_data

        try:
            s = Subscriper.objects.get(email=data['email'])
        except Subscriper.DoesNotExist:
            s = Subscriper()

        s.email = data['email']
        s.name = data['name']
        s.zip = data['zip']
        tmp = '%s%s' % (s.email,datetime.datetime.now())
        s.confirmkey = hashlib.md5(hashlib.md5(tmp).hexdigest()).hexdigest()
        s.save()
        return s

class TemplateForm(forms.Form):
    forwarder = forms.ChoiceField(choices=[(f.id, f.email) for f in Forwarder.objects.all()])
    subject = forms.CharField(max_length=50, required=True)
    message = forms.CharField(max_length=600, required=True,
            widget=forms.Textarea(attrs={'rows':'10','cols':'38'}))

    def __init__(self, *args, **kwargs):
        super(TemplateForm, self).__init__(*args, **kwargs)

    def save(self, request=None, **kwargs):
        data = self.cleaned_data

        t = Template(forwarder=Forwarder.objects.get(id=data['forwarder']),subject=data['subject'],message=data['message'])
        t.save()
        return t


text:
/**
 * This module provides all required forces to regular ngraph.physics.simulator
 * to make it 3D simulator. Ideally ngraph.physics.simulator should operate
 * with vectors, but on practices that showed performance decrease... Maybe
 * I was doing it wrong, will see if I can refactor/throw away this module.
 */
module.exports = createLayout;
createLayout.get2dLayout = require('ngraph.forcelayout');

function createLayout(graph, physicsSettings) {
  var merge = require('ngraph.merge');
  physicsSettings = merge(physicsSettings, {
        createQuadTree: require('ngraph.quadtreebh3d'),
        createBounds: require('./lib/bounds'),
        createDragForce: require('./lib/dragForce'),
        createSpringForce: require('./lib/springForce'),
        integrator: getIntegrator(physicsSettings),
        createBody: require('./lib/createBody')
      });

  return createLayout.get2dLayout(graph, physicsSettings);
}

function getIntegrator(physicsSettings) {
  if (physicsSettings && physicsSettings.integrator === 'verlet') {
    return require('./lib/verletIntegrator.js');
  }

  return require('./lib/eulerIntegrator')
}


text: Product Roadmap


text:
Installation
================

Install Vendors
-------------------
php bin/vendors install

Update database
-------------------

* Configured database is called symfony2social, user:root / password: empty (app/config/parameters.ini).

php app/console doctrine:schema:update --force

Facebook
-------------------
Included test Facebook app is configured for symfony2social.com domain.

You should edit your hosts config to resolve this domain in your hosts file.

sudo vi /etc/hosts

Admin
------------------
For admin dashboard go to:

/app_dev.php/admini/dashboard


text:
require File.expand_path(File.dirname(__FILE__) + "/application/test/test_helper.rb")

class HelperTest < ActionView::TestCase

  tests FSP::Helper

  def setup
    self.stubs(:session).returns(ActionController::TestSession.new)
  end

  test 'should generate page links with proper sorts' do
    params = {:page_size => "10", :page => "1", :filter => "0", :sorts => "FOO:bar", :controller => "widgets", :action => "index" }.with_indifferent_access
    fsp = FSP::FilterSortPaginate.new(Widget, params.merge({:url_writer => :widgets_path}))
    fsp.count = 100
    assert w = sort_header_tag(fsp, 'baz', :caption => 'Baz')
    assert x = pagination_links(fsp)
    assert_select_in x, "a", "2" do |link|
      assert_match /sorts=FOO%3Abar/, link.to_s
    end
  end

  private
  def assert_select_in(html, *args, &block)
    node = HTML::Document.new(html).root
    assert_select(*args.unshift(node), &block)
  end
end


text:
class ServerController < ApplicationController

  # CSRF-protection must be skipped, because incoming
  # OpenID requests lack an authenticity token
  skip_before_filter :verify_authenticity_token
  # Error handling
  rescue_from OpenID::Server::ProtocolError, :with => :render_openid_error
  # Actions other than index require a logged in user
  before_filter :login_required, :except => [:index, :cancel, :seatbelt_config, :seatbelt_login_state]
  before_filter :ensure_valid_checkid_request, :except => [:index, :cancel, :seatbelt_config, :seatbelt_login_state]
  after_filter :clear_checkid_request, :only => [:cancel, :complete]
  # These methods are used to display information about the request to the user
  helper_method :sreg_request, :ax_fetch_request, :ax_store_request

  # This is the server endpoint which handles all incoming OpenID requests.
  # Associate and CheckAuth requests are answered directly - functionality
  # therefor is provided by the ruby-openid gem. Handling of CheckId requests
  # dependents on the users login state (see handle_checkid_request).
  # Yadis requests return information about this endpoint.
  def index
    clear_checkid_request
    respond_to do |format|
      format.html do
        if openid_request.is_a?(OpenID::Server::CheckIDRequest)
          handle_checkid_request
        elsif openid_request
          handle_non_checkid_request
        else
          render :text => t(:this_is_openid_not_a_human_ressource)
        end
      end
      format.xrds
    end
  end

  # This action decides how to process the current request and serves as
  # dispatcher and re-entry in case the request could not be processed
  # directly (for instance if the user had to log in first).
  # When the user has already trusted the relying party, the request will
  # be answered based on the users release policy. If the request is immediate
  # (relying party wants no user interaction, used e.g. for ajax requests)
  # the request can only be answered if no further information (like simple
  # registration data) is requested. Otherwise the user will be redirected
  # to the decision page.
  def proceed
    identity = identifier(current_account)
    if @site = current_account.sites.find_by_url(checkid_request.trust_root)
      resp = checkid_request.answer(true, nil, identity)
      resp = add_sreg(resp, @site.sreg_properties) if sreg_request
      resp = add_ax(resp, @site.ax_properties) if ax_fetch_request
      resp = add_pape(resp, auth_policies, auth_level, auth_time)
      render_response(resp)
    elsif checkid_request.immediate && (sreg_request || ax_store_request || ax_fetch_request)
      render_response(checkid_request.answer(false))
    elsif checkid_request.immediate
      render_response(checkid_request.answer(true, nil, identity))
    else
      redirect_to decide_path
    end
  end

  # Displays the decision page on that the user can confirm the request and
  # choose which data should be transfered to the relying party.
  def decide
    @site = current_account.sites.find_or_initialize_by_url(checkid_request.trust_root)
    @site.persona = current_account.personas.find(params[:persona_id] || :first) if sreg_request || ax_store_request || ax_fetch_request
  end

  # This action is called by submitting the decision form, the information entered by
  # the user is used to answer the request. If the user decides to always trust the
  # relying party, a new site according to the release policies the will be created.
  def complete
    if params[:cancel]
      cancel
    else
      resp = checkid_request.answer(true, nil, identifier(current_account))
      if params[:always]
        @site = current_account.sites.find_or_create_by_persona_id_and_url(params[:site][:persona_id], params[:site][:url])
        @site.update_attributes(params[:site])
      elsif sreg_request || ax_fetch_request
        @site = current_account.sites.find_or_initialize_by_persona_id_and_url(params[:site][:persona_id], params[:site][:url])
        @site.attributes = params[:site]
      elsif ax_store_request
        @site = current_account.sites.find_or_initialize_by_persona_id_and_url(params[:site][:persona_id], params[:site][:url])
        not_supported, not_accepted, accepted = [], [], []
        ax_store_request.data.each do |type_uri, values|
          if property = Persona.attribute_name_for_type_uri(type_uri)
            store_attribute = params[:site][:ax_store][property.to_sym]
            if store_attribute && !store_attribute[:value].blank?
              @site.persona.update_attribute(property, values.first)
              accepted << type_uri
            else
              not_accepted << type_uri
            end
          else
            not_supported << type_uri
          end
        end
        ax_store_response = (accepted.count > 0) ? OpenID::AX::StoreResponse.new : OpenID::AX::StoreResponse.new(false, "None of the attributes were accepted.")
        resp.add_extension(ax_store_response)
      end
      resp = add_pape(resp, auth_policies, auth_level, auth_time)
      resp = add_sreg(resp, @site.sreg_properties) if sreg_request && @site.sreg_properties
      resp = add_ax(resp, @site.ax_properties) if ax_fetch_request && @site.ax_properties
      render_response(resp)
    end
  end

  # Cancels the current OpenID request
  def cancel
    redirect_to checkid_request.cancel_url
  end

  protected

  # Decides how to process an incoming checkid request. If the user is
  # already logged in he will be forwarded to the proceed action. If
  # the user is not logged in and the request is immediate, the request
  # cannot be answered successfully. In case the user is not logged in,
  # the request will be stored and the user is asked to log in.
  def handle_checkid_request
    if allow_verification?
      save_checkid_request
      redirect_to proceed_path
    elsif openid_request.immediate
      render_response(openid_request.answer(false))
    else
      reset_session
      request = save_checkid_request
      session[:return_to] = proceed_path
      redirect_to( request.from_trusted_domain? ? login_path : safe_login_path )
    end
  end

  # Stores the current OpenID request.
  # Returns the OpenIdRequest
  def save_checkid_request
    clear_checkid_request
    request = OpenIdRequest.create(:parameters => openid_params)
    session[:request_token] = request.token

    request
  end

  # Deletes the old request when a new one comes in.
  def clear_checkid_request
    unless session[:request_token].blank?
      OpenIdRequest.destroy_all :token => session[:request_token]
      session[:request_token] = nil
    end
  end

  # Use this as before_filter for every CheckID request based action.
  # Loads the current openid request and cancels if none can be found.
  # The user has to log in, if he has not verified his ownership of
  # the identifier, yet.
  def ensure_valid_checkid_request
    self.openid_request = checkid_request
    if !openid_request.is_a?(OpenID::Server::CheckIDRequest)
      redirect_to root_path, :alert => t(:identity_verification_request_invalid)
    elsif !allow_verification?
      flash[:notice] = logged_in? && !pape_requirements_met?(auth_time) ?
        t(:service_provider_requires_reauthentication_last_login_too_long_ago) :
        t(:login_to_verify_identity)
      session[:return_to] = proceed_path
      redirect_to login_path
    end
  end

  # The user must be logged in, he must be the owner of the claimed identifier
  # and the PAPE requirements must be met if applicable.
  def allow_verification?
    logged_in? && correct_identifier? && pape_requirements_met?(auth_time)
  end

  # Is the user allowed to verify the claimed identifier? The user
  # must be logged in, so that we know his identifier or the identifier
  # has to be selected by the server (id_select).
  def correct_identifier?
    (openid_request.identity == identifier(current_account) || openid_request.id_select)
  end

  # Clears the stored request and answers
  def render_response(resp)
    clear_checkid_request
    render_openid_response(resp)
  end

  # Transforms the parameters from the form to valid AX response values
  def transform_ax_data(parameters)
    data = {}
    parameters.each_pair do |key, details|
      if details['value']
        data["type.#{key}"] = details['type']
        data["value.#{key}"] = details['value']
      end
    end
    data
  end

  # Renders the exception message as text output
  def render_openid_error(exception)
    error = case exception
    when OpenID::Server::MalformedTrustRoot then "Malformed trust root '#{exception.to_s}'"
    else exception.to_s
    end
    render :text => "Invalid OpenID request: #{error}", :status => 500
  end

  private

  # The NIST Assurance Level, see:
  # http://openid.net/specs/openid-provider-authentication-policy-extension-1_0-01.html#anchor12
  def auth_level
    if Masquerade::Application::Config['use_ssl']
      current_account.last_authenticated_with_yubikey? ? 3 : 2
    else
      0
    end
  end

  def auth_time
    current_account.last_authenticated_at
  end

  def auth_policies
    current_account.last_authenticated_with_yubikey? ?
      [OpenID::PAPE::AUTH_MULTI_FACTOR, OpenID::PAPE::AUTH_PHISHING_RESISTANT] :
      []
  end

end


text:
using System;
using System.Buffers;
using Newtonsoft.Json;

namespace Jasper.Runtime.Serialization;

internal class JsonArrayPool<T> : IArrayPool<T>
{
    private readonly ArrayPool<T> _inner;

    public JsonArrayPool(ArrayPool<T> inner)
    {
        _inner = inner ?? throw new ArgumentNullException(nameof(inner));
    }

    public T[] Rent(int minimumLength)
    {
        return _inner.Rent(minimumLength);
    }

#pragma warning disable CS8767
    public void Return(T[] array)
#pragma warning restore CS8767
    {
        if (array == null)
        {
            throw new ArgumentNullException(nameof(array));
        }

        _inner.Return(array);
    }
}


text:
<SageTVPlugin>
  <Name>Replace Index Numbers with Season/Episode in Recordings Screen</Name>
  <Identifier>RRNWSE</Identifier>
  <Description>Replaces the numbers in the recordings group information with the Season and Episode number</Description>
  <Author>toricred</Author>
  <CreationDate>2010-11-06</CreationDate>
  <ModificationDate>2010.04.09</ModificationDate>
  <Version>0.3</Version>
  <Desktop>false</Desktop>
  <PluginType>STVI</PluginType>
  <STVImport>RecordingGroupsNoNumsSE.stvi</STVImport>
  <Screenshot>http://storage.googleapis.com/google-code-archive-downloads/v2/code.google.com/rrnwse/ScreenShot.jpg</Screenshot>
  <Package>
    <PackageType>STVI</PackageType>
   <Location>https://github.com/OpenSageTV/sagetv-plugin-repo/releases/download/1/RecordingGroupsNoNumsSE.zip</Location>
    <MD5>1A9C6CB6E75D8D3FDACD89842C5D5C03</MD5>
  </Package>
</SageTVPlugin>


text: require "google/apis/androiddeviceprovisioning_v1"


text:
/*! \file uidentd.cc
	Micro ident daemon
*/
#include <uidentd.hh>

namespace Sasayaku {
	uidentd::uidentd(void) {
		running = false;
	}

	uidentd::~uidentd(void) {

	}

	bool uidentd::start(void) {
		if(this->identd == nullptr) {
			running = true;
			this->identd = new std::thread(uidentd::identServer);
			return true;
		} else {
			return false;
		}
	}
	void uidentd::stop(void) {
		running = false;
	}

	void uidentd::identServer(void) {
		// Setup server
		int socket, conn;
		struct addrinfo hints, *servinfo, *p;
		struct sockaddr_storage addrs;
		socklen_t ssize;
		struct sigaction sa;
		char s[INET6_ADDRSTRLEN];
		int rv;

		memset(&hints, 0, sizeof(hints));
		hints.ai_family = AF_UNSPEC;
		hints.ai_socktype = SOCK_STREAM;
		hints.ai_flags = AI_PASSIVE;

		if((rv = getaddrinfo(NULL, this->port, &hints, &servinfo)) != 0) {

			return;
		}
		// Handle requests
		while(running) {

		}
	}
}


text:
'use strict';

const dotenv = require('dotenv');
const cors = require('cors');
const morgan = require('morgan');
const mongoose = require('mongoose');
const express = require('express');
const debug = require('debug')('alexa-skillz:server');
const bodyParser = require('body-parser');
const expressSession = require('express-session');
const cookieParser = require('cookie-parser');
const User = require('./model/user.js');

const authRouter = require('./route/auth-router.js');
const answerRouter = require('./route/answer-router.js');
const userRouter = require('./route/user-router.js');
const questionRouter = require('./route/question-router.js');
const errors = require('./lib/error-middleware.js');

const passport = require('passport');
require('./config/passport');

require('./model/answer');
require('./model/question');
require('./model/user');

const app = express();

if(process.env.NODE_ENV !== 'production') dotenv.load();

const PORT = process.env.PORT || 3000;

app.use(express.static('public'));
app.use(cookieParser());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(expressSession({
  secret: 'secret',
  saveUninitialized: true,
  resave: true
}));
app.use(passport.initialize());
app.use(passport.session());
passport.serializeUser(function(user, done) {
  done(null, user.id);
});
passport.deserializeUser(function(id, done) {
  User.findById(id, function(err, user) {
    done(null, user);
  });
});

mongoose.Promise = Promise;
mongoose.connect(process.env.MONGODB_URI);

app.use(cors());
app.use(morgan('dev'));

app.use(authRouter);
app.use(answerRouter);
app.use(userRouter);
app.use(questionRouter);
app.use(errors);

const server = module.exports = app.listen(PORT, () => {
  debug(`server is up at port: ${PORT}`);
});

server.isRunning = true;


text:
package chrome.management

import chrome.ChromeAPI
import chrome.events.EventSource
import chrome.events.EventSourceImplicits._
import chrome.management.bindings.ExtensionInfo._
import chrome.management.bindings._
import chrome.permissions.APIPermission
import chrome.runtime.bindings.Runtime.AppID
import utils.ErrorHandling.lastErrorOrValue

import scala.concurrent.{Future, Promise}
import scala.scalajs.js

object Management extends ChromeAPI {

  val requiredPermissions: Set[APIPermission] = Set(APIPermission.Management)

  val onInstalled: EventSource[ExtensionInfo] = bindings.Management.onInstalled
  val onUninstalled: EventSource[String] = bindings.Management.onUninstalled
  val onEnabled: EventSource[ExtensionInfo] = bindings.Management.onEnabled
  val onDisabled: EventSource[ExtensionInfo] = bindings.Management.onDisabled

  def getAll: Future[js.Array[ExtensionInfo]] = {
    val promise = Promise[js.Array[ExtensionInfo]]()
    bindings.Management.getAll((extensions: js.Array[ExtensionInfo]) => {
      promise.complete(lastErrorOrValue(extensions))
    })
    promise.future
  }

  def get(id: AppID): Future[ExtensionInfo] = {
    val promise = Promise[ExtensionInfo]()
    bindings.Management.get(id, (extension: ExtensionInfo) => {
      promise.complete(lastErrorOrValue(extension))
    })
    promise.future
  }

  def getSelf: Future[ExtensionInfo] = {
    val promise = Promise[ExtensionInfo]()
    bindings.Management.getSelf((self: ExtensionInfo) => {
      promise.complete(lastErrorOrValue(self))
    })
    promise.future
  }

  def getPermissionWarningsById(id: AppID): Future[js.Array[String]] = {
    val promise = Promise[js.Array[String]]()
    bindings.Management.getPermissionWarningsById(id, (warnings: js.Array[String]) => {
      promise.complete(lastErrorOrValue(warnings))
    })
    promise.future
  }

  def getPermissionWarningsByManifest(manifestStr: String): Future[js.Array[String]] = {
    val promise = Promise[js.Array[String]]()
    bindings.Management.getPermissionWarningsByManifest(manifestStr, (warnings: js.Array[String]) => {
      promise.complete(lastErrorOrValue(warnings))
    })
    promise.future
  }

  def setEnabled(id: AppID, enabled: Boolean): Future[Boolean] = {
    val promise = Promise[Boolean]()
    bindings.Management.setEnabled(id, enabled, js.Any.fromFunction0(() => {
      promise.complete(lastErrorOrValue(enabled))
    }))
    promise.future
  }

  def uninstall(id: AppID, options: js.UndefOr[js.Object] = js.undefined): Future[Unit] = {
    val promise = Promise[Unit]()
    bindings.Management.uninstall(id, options, js.Any.fromFunction0(() => {
      promise.complete(lastErrorOrValue(()))
    }))
    promise.future
  }

  def uninstallSelf(options: js.UndefOr[js.Object] = js.undefined,
                    callback: js.UndefOr[js.Function0[_]] = js.undefined): Future[Unit] = {
    val promise = Promise[Unit]()
    bindings.Management.uninstallSelf(options, js.Any.fromFunction0(() => {
      promise.complete(lastErrorOrValue(()))
    }))
    promise.future
  }

  def launchApp(id: AppID): Future[Unit] = {
    val promise = Promise[Unit]()
    bindings.Management.launchApp(id, js.Any.fromFunction0(() => {
      promise.complete(lastErrorOrValue(()))
    }))
    promise.future
  }

  def createAppShortcut(id: AppID): Future[Unit] = {
    val promise = Promise[Unit]()
    bindings.Management.createAppShortcut(id, js.Any.fromFunction0(() => {
      promise.complete(lastErrorOrValue(()))
    }))
    promise.future
  }

  def setLaunchType(id: AppID, launchType: LaunchType): Future[Unit] = {
    val promise = Promise[Unit]()
    bindings.Management.setLaunchType(id, launchType, js.Any.fromFunction0(() => {
      promise.complete(lastErrorOrValue(()))
    }))
    promise.future
  }

  def generateAppForLink(url: String, title: String): Future[ExtensionInfo] = {
    val promise = Promise[ExtensionInfo]()
    bindings.Management.generateAppForLink(url, title, js.Any.fromFunction1((info: ExtensionInfo) => {
      promise.complete(lastErrorOrValue(info))
    }))
    promise.future
  }

}


text:
myApp
    .factory('Products', ['$resource',productsFactory])
    .factory('Product',['$resource',productFactory])
    .factory('ProductSearch',['$resource',ProductSearch])
    .factory('expirationProducts',['$resource',expirationProducts])

function productFactory($resource){
    return $resource('/products/:id.json',{},{
        show: { method: 'GET' },
        update: { method: 'PUT', params: {id: '@id'} },
        delete: { method: 'DELETE', params: {id: '@id'}}
    });
}

function productsFactory($resource){
    return $resource('/products.json',{},{
        query: { method: 'GET', isArray: true },
        create: { method: 'POST' }
    });
}

function ProductSearch($resource){
    return $resource('/products.json?search=:query&filter=:filter', {},{
    query: { method: 'GET', params: {query: '@query', filter:'@filter'} ,isArray: true }
    });
}

function expirationProducts($resource){
    return $resource('/report_expiration.json',{},{
        query: { method: 'GET', isArray: true }
    });
}


text:
"use strict";

// Require all test suites here.
require('./testHarness');
require('./testFetchAndReplace');
require('./testSavedState');
require('./testUtil');


text:
package in.zapr.druid.druidry.aggregator;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import org.json.JSONException;
import org.json.JSONObject;
import org.skyscreamer.jsonassert.JSONAssert;
import org.skyscreamer.jsonassert.JSONCompareMode;
import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class LongMaxAggregatorTest {

    private static ObjectMapper objectMapper;

    @BeforeClass
    public void init() {
        objectMapper = new ObjectMapper();
    }

    @Test
    public void testAllFields() throws JsonProcessingException, JSONException {

        LongMaxAggregator countAggregator = new LongMaxAggregator("CarpeDiem",
                "Hey");

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("type", "longMax");
        jsonObject.put("name", "CarpeDiem");
        jsonObject.put("fieldName", "Hey");

        String actualJSON = objectMapper.writeValueAsString(countAggregator);
        String expectedJSON = jsonObject.toString();
        JSONAssert.assertEquals(expectedJSON, actualJSON, JSONCompareMode.NON_EXTENSIBLE);
    }

    @Test
    public void testAllFieldsButFieldName() throws JsonProcessingException, JSONException {

        LongMaxAggregator countAggregator =
            LongMaxAggregator.builder()
                .name("CarpeDiem")
                .expression("(\"foo\" / \"bar\")")
                .build();

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("type", "longMax");
        jsonObject.put("name", "CarpeDiem");
        jsonObject.put("expression", "(\"foo\" / \"bar\")");

        String actualJSON = objectMapper.writeValueAsString(countAggregator);
        String expectedJSON = jsonObject.toString();
        JSONAssert.assertEquals(expectedJSON, actualJSON, JSONCompareMode.NON_EXTENSIBLE);
    }

    @Test(expectedExceptions = NullPointerException.class)
    public void testNullName() throws JsonProcessingException, JSONException {

        LongMaxAggregator longMaxAggregator =
            LongMaxAggregator.builder()
                .fieldName("Haha")
                .build();
    }

    @Test
    public void testEqualsPositive() {
        LongMaxAggregator aggregator1 =
            LongMaxAggregator.builder()
                .name("name")
                .fieldName("field")
                .build();

        LongMaxAggregator aggregator2 =
            LongMaxAggregator.builder()
                .name("name")
                .fieldName("field")
                .build();

        LongMaxAggregator aggregator3 =
            LongMaxAggregator.builder()
                .name("name")
                .expression("(\"foo\" / \"bar\")")
                .build();

        LongMaxAggregator aggregator4 =
            LongMaxAggregator.builder()
                .name("name")
                .expression("(\"foo\" / \"bar\")")
                .build();

        Assert.assertEquals(aggregator1, aggregator2);
        Assert.assertEquals(aggregator3, aggregator4);
    }

    @Test
    public void testEqualsNegative() {
        LongMaxAggregator aggregator1 =
            LongMaxAggregator.builder()
                .name("name")
                .fieldName("field")
                .build();

        LongMaxAggregator aggregator2 =
            LongMaxAggregator.builder()
                .name("name1")
                .fieldName("field1")
                .build();

        LongMaxAggregator aggregator3 =
            LongMaxAggregator.builder()
                .name("name")
                .expression("(\"foo\" / \"bar\")")
                .build();

        LongMaxAggregator aggregator4 =
            LongMaxAggregator.builder()
                .name("name")
                .expression("(\"foo\" / \"baz\")")
                .build();

        Assert.assertNotEquals(aggregator1, aggregator2);
        Assert.assertNotEquals(aggregator3, aggregator4);
    }

    @Test
    public void testEqualsWithAnotherSubClass() {
        LongMaxAggregator aggregator1 =
            LongMaxAggregator.builder()
                .name("name")
                .fieldName("field")
                .build();

        CountAggregator aggregator2 = new CountAggregator("countAgg1");

        Assert.assertNotEquals(aggregator1, aggregator2);
    }

}


text:
package org.mockito.internal.runners.util;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

import org.mockito.internal.runners.RunnerImpl;

public class RunnerProvider {

    private static boolean hasJUnit45OrHigher;

    static {
        try {
            Class.forName("org.junit.runners.BlockJUnit4ClassRunner");
            hasJUnit45OrHigher = true;
        } catch (Throwable t) {
            hasJUnit45OrHigher = false;
        }
    }

    public boolean isJUnit45OrHigherAvailable() {
        return hasJUnit45OrHigher;
    }

    public RunnerImpl newInstance(String runnerClassName, Class<?> constructorParam) throws Exception {
        Constructor<?> constructor;
        try {
            Class<?> runnerClass = Class.forName(runnerClassName);
            constructor = runnerClass.getConstructor(Class.class.getClass());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        try {
            return (RunnerImpl) constructor.newInstance(constructorParam);
        } catch (InvocationTargetException e) {
            throw e;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}


text:
'use strict';
var redis = require('redis');
var RedisClient =  redis.RedisClient;
require('cofy').class(RedisClient);

RedisClient.prototype.$getJson = function(key){
	var _this = this;
	return function(done){
		_this.get(key, function(e,r){
			if(e){
				return done(e);
			}
			try{
				done(null ,JSON.parse(r));
			}catch(e){
				done(null , r);
			}

		});
	};
};

RedisClient.prototype.$setJson = function(key,object){
	var _this = this;
	return function(done){
		_this.set(key,JSON.stringify(object),done);
	};
};
module.exports = redis;


text:
<?php
	declare(strict_types=1);

	namespace Framework\Syscrack\Game\Softwares;

	/**
	 * Lewis Lancaster 2017
	 *
	 * Class ForceDownload
	 *
	 * @package Framework\Syscrack\Game\Softwares
	 */

	use Framework\Syscrack\Game\Bases\BaseSoftware;
	use Framework\Syscrack\Game\Tool;

	/**
	 * Class ForceDownload
	 * @package Framework\Syscrack\Game\Softwares
	 */
	class ForceDownload extends BaseSoftware
	{

		/**
		 * The configuration of this Structure
		 *
		 * @return array
		 */

		public function configuration()
		{

			return [
				'uniquename' => 'forceupload',
				'extension' => '.admin',
				'type' => 'admin',
				'installable' => true,
				'executable' => true,
				'localexecuteonly' => true,
			];
		}

		/**
		 * @param null $userid
		 * @param null $sofwareid
		 * @param null $computerid
		 *
		 * @return Tool
		 */

		public function tool($userid = null, $sofwareid = null, $computerid = null): Tool
		{

			$tool = new Tool("Force Download", "danger");
			$tool->admin();
			$tool->setAction('forcedownload');
			$tool->addInput("softwareid", "softwares");
			$tool->panel("danger");
			$tool->icon = "arrow-up";

			return ($tool);
		}
	}


text:
# Mean

> [Arcsine][arcsine-distribution] distribution [expected value][expected-value].

The [expected value][expected-value] for an [arcsine][arcsine-distribution] random variable is

where `a` is the minimum support and `b` is the maximum support.

## Usage

```javascript
var mean = require( '@stdlib/stats/base/dists/arcsine/mean' );
```

#### mean( a, b )

Returns the [expected value][expected-value] of an [arcsine][arcsine-distribution] distribution with parameters `a` (minimum support) and `b` (maximum support).

```javascript
var v = mean( 0.0, 1.0 );
// returns 0.5

v = mean( 4.0, 12.0 );
// returns 8.0

v = mean( 2.0, 8.0 );
// returns 5.0
```

If provided `NaN` as any argument, the function returns `NaN`.

```javascript
var v = mean( NaN, 2.0 );
// returns NaN

v = mean( 2.0, NaN );
// returns NaN
```

If provided `a >= b`, the function returns `NaN`.

```javascript
var y = mean( 3.0, 2.0 );
// returns NaN

y = mean( 3.0, 3.0 );
// returns NaN
```

## Examples

```javascript
var randu = require( '@stdlib/random/base/randu' );
var mean = require( '@stdlib/stats/base/dists/arcsine/mean' );

var a;
var b;
var v;
var i;

for ( i = 0; i < 10; i++ ) {
    a = ( randu()*10.0 );
    b = ( randu()*10.0 ) + a;
    v = mean( a, b );
    console.log( 'a: %d, b: %d, E(X;a,b): %d', a.toFixed( 4 ), b.toFixed( 4 ), v.toFixed( 4 ) );
}
```

[arcsine-distribution]: https://en.wikipedia.org/wiki/Arcsine_distribution

[expected-value]: https://en.wikipedia.org/wiki/Expected_value


text:
class CoreUtilsTest : public ::testing::Test {
public:
    CoreUtilsTest() : constSizeFileName(TestHelpers::resolvePath("file_with_const_size.png")) {

    }
protected:
    const std::string constSizeFileName;
    const int64_t contSizeFileSize = 14830;
};

using namespace IuCoreUtils;

TEST_F(CoreUtilsTest, ExtractFilePath)
{
    std::string fileName = "c:\\Program Files (x86)\\Image Uploader\\Image Uploader.exe";
    std::string result = ExtractFilePath(fileName);
    EXPECT_EQ("c:\\Program Files (x86)\\Image Uploader\\", result);
    result = ExtractFilePath("c:/Program Files (x86)\\Image Uploader/ExplorerIntegration64.dll");
    EXPECT_EQ("c:/Program Files (x86)\\Image Uploader/", result);
    result = ExtractFilePath("avcodec-56.dll");
    EXPECT_EQ("", result);
}

TEST_F(CoreUtilsTest, ExtractFileName)
{
    std::string fileName = "c:\\Program Files (x86)\\Image Uploader\\Image Uploader.exe";
    std::string result = ExtractFileName(fileName);
    EXPECT_EQ(result, "Image Uploader.exe");
    result = ExtractFileName("c:/Program Files (x86)\\Image Uploader/ExplorerIntegration64.dll");
    EXPECT_EQ(result, "ExplorerIntegration64.dll");
    result = ExtractFileName("avcodec-56.dll");
    EXPECT_EQ(result, "avcodec-56.dll");
}

TEST_F(CoreUtilsTest, ExtractFileExt)
{
    std::string fileName = "c:\\Program Files (x86)\\Image Uploader\\Image Uploader.exe";
    std::string result = ExtractFileExt(fileName);
    EXPECT_EQ(result, "exe");
    result = ExtractFileExt("c:/Program Files (x86)\\Image Uploader/ExplorerIntegration64.dll");
    EXPECT_EQ(result, "dll");
    result = ExtractFileExt("c:\\Program Files .(x86)\\Image Uploader.exe\\Image Uploader");
    EXPECT_EQ(result, "");
    result = ExtractFileExt("archive.tar.gz");
    EXPECT_EQ(result, "gz");
}

TEST_F(CoreUtilsTest, ExtractFileNameNoExt)
{
    std::string fileName = "c:\\Program Files (x86)\\Image Uploader\\Image Uploader.exe";
    std::string result = ExtractFileNameNoExt(fileName);
    EXPECT_EQ(result, "Image Uploader");
    result = ExtractFileNameNoExt("c:/Program Files (x86)\\Image Uploader/ExplorerIntegration64.dll");
    EXPECT_EQ(result, "ExplorerIntegration64");
    result = ExtractFileNameNoExt("c:\\Program Files .(x86)\\Image Uploader.exe\\Image Uploader");
    EXPECT_EQ(result, "Image Uploader");
    result = ExtractFileNameNoExt("archive.tar.gz");
    EXPECT_EQ(result, "archive.tar");
}

TEST_F(CoreUtilsTest, ExtractFileNameFromUrl)
{
    std::string result = ExtractFileNameFromUrl("http://www.directupload.net/file/d/3970/vmtbrege_jpg.htm");
    EXPECT_EQ("vmtbrege_jpg.htm", result);
    result = ExtractFileNameFromUrl("http://www.directupload.net/file/d/3970/vmtbrege_jpg.html?test=124&grgrg=54+5435");
    EXPECT_EQ("vmtbrege_jpg.html", result);

}

TEST_F(CoreUtilsTest, toString)
{
   // std::string result = toString(100);

    EXPECT_EQ(toString(100), "100");
    EXPECT_EQ(toString(2147483647), "2147483647");
    EXPECT_EQ(toString(-2147483646), "-2147483646");
    EXPECT_EQ(toString(0), "0");
    EXPECT_EQ(toString((unsigned int)0xffffffff), "4294967295");
    EXPECT_EQ(toString(100.5, 2), "100.50");
    EXPECT_EQ(toString(100.54534, 0), "101");
}

TEST_F(CoreUtilsTest, int64_tToString)
{
    EXPECT_EQ("-2147483648", int64_tToString(std::numeric_limits<int>::min()));
    EXPECT_EQ(int64_tToString(INT64_MAX), "9223372036854775807");
    EXPECT_EQ("-9223372036854775808", int64_tToString(INT64_MIN));
    EXPECT_EQ("-9223372036854775807", int64_tToString(INT64_MIN + 1) );

    EXPECT_EQ(int64_tToString(0), "0");
}

TEST_F(CoreUtilsTest, stringToint64_t)
{
    EXPECT_TRUE(stringToInt64("9223372036854775807")== 9223372036854775807);
    EXPECT_TRUE(stringToInt64("-9223372036854775807") == INT64_C(-9223372036854775807));
    EXPECT_TRUE(stringToInt64("0")== 0);
}

TEST_F(CoreUtilsTest, GetDefaultExtensionForMimeType)
{
    EXPECT_EQ("gif", GetDefaultExtensionForMimeType("image/gif"));
    EXPECT_EQ("png", GetDefaultExtensionForMimeType("image/png"));
    EXPECT_EQ("jpg", GetDefaultExtensionForMimeType("image/jpeg"));
    EXPECT_EQ("webp", GetDefaultExtensionForMimeType("image/webp"));
    EXPECT_EQ("", GetDefaultExtensionForMimeType("application/unknown"));
}

TEST_F(CoreUtilsTest, fileSizeToString)
{
    EXPECT_EQ(fileSizeToString(140*1024*1024), "140.0 MB");
    EXPECT_EQ(fileSizeToString(static_cast<int64_t>(25.5*1024)), "26 KB");
    EXPECT_EQ(fileSizeToString(0), "0 bytes");
}

TEST_F(CoreUtilsTest, Utf8ToWstring)
{
    std::wstring result = Utf8ToWstring("\x49\xC3\xB1\x74\xC3\xAB\x72\x6E\xC3\xA2\x74\x69\xC3\xB4\x6E\xC3\xA0\x6C\x69\x7A\xC3\xA6\x74\x69\xC3\xB8\x6E");
    EXPECT_EQ(result, L"I\u00F1t\u00EBrn\u00E2ti\u00F4n\u00E0liz\u00E6ti\u00F8n");
    result = Utf8ToWstring("");
    EXPECT_EQ(result, L"");
    result = Utf8ToWstring("test test");
    EXPECT_EQ(result, L"test test");
}

TEST_F(CoreUtilsTest, getFileSize)
{
    int64_t size = IuCoreUtils::getFileSize("not_existing_file22342343");
    EXPECT_EQ(size, -1);
    ASSERT_TRUE(IuCoreUtils::FileExists(constSizeFileName));
    size = IuCoreUtils::getFileSize(constSizeFileName);
    EXPECT_EQ(size, contSizeFileSize);
}

TEST_F(CoreUtilsTest, copyFile)
{
    std::string destFile = TestHelpers::resolvePath("AnotherFolder/new_file.png");
    ASSERT_TRUE(IuCoreUtils::FileExists(constSizeFileName));
    bool res = IuCoreUtils::copyFile(constSizeFileName, destFile, true);
    EXPECT_EQ(res, true);
    EXPECT_EQ(IuCoreUtils::FileExists(destFile), true);
    int64_t size = IuCoreUtils::getFileSize(destFile);
    EXPECT_EQ(size, contSizeFileSize);
}

#ifdef _WIN32
TEST_F(CoreUtilsTest, gettimeofday)
{
    struct timeval tp;
    gettimeofday(&tp, NULL);
    int64_t curTime = tp.tv_sec * 1000 + tp.tv_usec / 1000;
    gettimeofday(&tp, NULL);
    int64_t curTime2 = tp.tv_sec * 1000 + tp.tv_usec / 1000;
    EXPECT_GE(curTime2, curTime2);
}
#endif

TEST_F(CoreUtilsTest, ReadUtf8TextFile)
{
    std::string file = TestHelpers::resolvePath("utf8_text_file_with_bom.txt");
    ASSERT_TRUE(IuCoreUtils::FileExists(file));
    std::string data;
    EXPECT_TRUE(ReadUtf8TextFile(file, data));
    EXPECT_EQ("Test file with bom. \xD0\xA2\xD0\xB5\xD1\x81\xD1\x82\xD0\xBE\xD0\xB2\xD1\x8B\xD0\xB9 \xD1\x84\xD0\xB0\xD0\xB9\xD0\xBB \xD1\x81 BOM.", data);

    std::string file2 = TestHelpers::resolvePath("utf8_text_file.txt");
    std::string data2;
    EXPECT_TRUE(ReadUtf8TextFile(file2, data2));
    EXPECT_EQ("Test file without bom. \xD0\xA2\xD0\xB5\xD1\x81\xD1\x82\xD0\xBE\xD0\xB2\xD1\x8B\xD0\xB9 \xD1\x84\xD0\xB0\xD0\xB9\xD0\xBB \xD0\xB1\xD0\xB5\xD0\xB7 BOM.", data2);

    std::string file3 = TestHelpers::resolvePath("file_with_zero_size.dat");
    std::string data3;
    EXPECT_TRUE(ReadUtf8TextFile(file3, data3));
    EXPECT_EQ("", data3);

    std::string file4 = TestHelpers::resolvePath("utf16_text_file.txt");
    std::string data4;
    EXPECT_TRUE(ReadUtf8TextFile(file4, data4));
    EXPECT_EQ("Test file in UTF16-LE. \xD0\xA2\xD0\xB5\xD1\x81\xD1\x82\xD0\xBE\xD0\xB2\xD1\x8B\xD0\xB9 \xD1\x84\xD0\xB0\xD0\xB9\xD0\xBB.", data4);

    std::string file5 = TestHelpers::resolvePath("not_existing_file226546546343");
    std::string data5;
    EXPECT_FALSE(ReadUtf8TextFile(file5, data5));
}

TEST_F(CoreUtilsTest, GetFileContents)
{
    ASSERT_TRUE(IuCoreUtils::FileExists(constSizeFileName));
    std::string data = GetFileContents(constSizeFileName);
    EXPECT_EQ(contSizeFileSize, data.size());
    std::string hash = IuCoreUtils::CryptoUtils::CalcMD5Hash(&data[0], data.size());
    EXPECT_EQ("ebbd98fc18bce0e9dd774f836b5c3bf8", hash);
}

TEST_F(CoreUtilsTest, GetFileMimeType) {
    ASSERT_TRUE(IuCoreUtils::FileExists(constSizeFileName));
    std::string type = GetFileMimeType(constSizeFileName);
    ASSERT_EQ("image/png", type);

    std::string webpFilePath = TestHelpers::resolvePath("Images/poroshok.webp");
    ASSERT_TRUE(IuCoreUtils::FileExists(webpFilePath));
    std::string type2 = GetFileMimeType(webpFilePath);
    ASSERT_EQ("image/webp", type2);
}


text:
'use strict';

/* Controllers */

angular.module('<%= appCamelizeName %>.controllers', [])
   .controller('HomeCtrl', ['$scope', 'syncData','loginService', function($scope, syncData, loginService) {
      syncData('syncedValue').$bind($scope, 'syncedValue');
      $scope.logout = function() {
         loginService.logout();
      };
   }])

  .controller('ChatCtrl', ['$scope', 'syncData', 'loginService', function($scope, syncData, loginService) {
      $scope.newMessage = null;

      // constrain number of messages by limit into syncData
      // add the array into $scope.messages
      $scope.messages = syncData('messages', 10);

      // add new messages to the list
      $scope.addMessage = function() {
         if( $scope.newMessage ) {
            $scope.messages.$add({text: $scope.newMessage});
            $scope.newMessage = null;
         }
      };

      $scope.logout = function() {
         loginService.logout();
      };
   }])

   .controller('LoginCtrl', ['$scope', 'loginService', '$location', function($scope, loginService, $location) {
      $scope.email = null;
      $scope.pass = null;
      $scope.confirm = null;
      $scope.createMode = false;

      $scope.login = function(cb) {
         $scope.err = null;
         if( !$scope.email ) {
            $scope.err = 'Please enter an email address';
         }
         else if( !$scope.pass ) {
            $scope.err = 'Please enter a password';
         }
         else {
            loginService.login($scope.email, $scope.pass, function(err, user) {
               $scope.err = err? err + '' : null;
               if( !err ) {
                  if(cb && cb(null))
                  {
                     return true;
                  }
                  else
                  {
                     return false;
                  }
               }
            });
         }
      };

      $scope.createAccount = function() {
         $scope.err = null;
         if( assertValidLoginAttempt() ) {
            loginService.createAccount($scope.email, $scope.pass, function(err, user) {
               if( err ) {
                  $scope.err = err? err + '' : null;
               }
               else {
                  // must be logged in before I can write to my profile
                  $scope.login(function() {
                     loginService.createProfile(user.uid, user.email);
                     $location.path('/account');
                  });
               }
            });
         }
      };

      function assertValidLoginAttempt() {
         if( !$scope.email ) {
            $scope.err = 'Please enter an email address';
         }
         else if( !$scope.pass ) {
            $scope.err = 'Please enter a password';
         }
         else if( $scope.pass !== $scope.confirm ) {
            $scope.err = 'Passwords do not match';
         }
         return !$scope.err;
      }
   }])

   .controller('AccountCtrl', ['$scope', 'loginService', 'changeEmailService', 'firebaseRef', 'syncData', '$location', 'FBURL', function($scope, loginService, changeEmailService, firebaseRef, syncData, $location, FBURL) {
      $scope.syncAccount = function() {
         $scope.user = {};
         syncData(['users', $scope.auth.user.uid]).$bind($scope, 'user').then(function(unBind) {
            $scope.unBindAccount = unBind;
         });
      };
      // set initial binding
      $scope.syncAccount();

      $scope.logout = function() {
         loginService.logout();
      };

      $scope.oldpass = null;
      $scope.newpass = null;
      $scope.confirm = null;

      $scope.reset = function() {
         $scope.err = null;
         $scope.msg = null;
         $scope.emailerr = null;
         $scope.emailmsg = null;
      };

      $scope.updatePassword = function() {
         $scope.reset();
         loginService.changePassword(buildPwdParms());
      };

      $scope.updateEmail = function() {
        $scope.reset();
        // disable bind to prevent junk data being left in firebase
        $scope.unBindAccount();
        changeEmailService(buildEmailParms());
      };

      function buildPwdParms() {
         return {
            email: $scope.auth.user.email,
            oldpass: $scope.oldpass,
            newpass: $scope.newpass,
            confirm: $scope.confirm,
            callback: function(err) {
               if( err ) {
                  $scope.err = err;
               }
               else {
                  $scope.oldpass = null;
                  $scope.newpass = null;
                  $scope.confirm = null;
                  $scope.msg = 'Password updated!';
               }
            }
         };
      }
      function buildEmailParms() {
         return {
            newEmail: $scope.newemail,
            pass: $scope.pass,
            callback: function(err) {
               if( err ) {
                  $scope.emailerr = err;
                  // reinstate binding
                  $scope.syncAccount();
               }
               else {
                  // reinstate binding
                  $scope.syncAccount();
                  $scope.newemail = null;
                  $scope.pass = null;
                  $scope.emailmsg = 'Email updated!';
               }
            }
         };
      }

   }]);


text:
from rpython.rlib import rfloat
from rpython.rlib.rstruct.ieee import float_pack

from topaz.objects.floatobject import W_FloatObject
from topaz.objects.intobject import W_FixnumObject

def make_float_packer(size, bigendian):
    def pack_float(space, packer, repetitions):
        if repetitions > len(packer.args_w) - packer.args_index:
            raise space.error(space.w_ArgumentError, "too few arguments")
        for i in xrange(packer.args_index, repetitions + packer.args_index):
            w_item = packer.args_w[i]
            if not (isinstance(w_item, W_FloatObject) or isinstance(w_item, W_FixnumObject)):
                raise space.error(space.w_TypeError,
                    "can't convert %s into Float" % space.obj_to_s(space.getclass(w_item))
                )
            doubleval = space.float_w(w_item)
            l = ["\0"] * size
            try:
                unsigned = float_pack(doubleval, size)
            except OverflowError:
                unsigned = float_pack(rfloat.copysign(rfloat.INFINITY, doubleval), size)
            for i in xrange(size):
                l[i] = chr((unsigned >> (i * 8)) & 0xff)
            if bigendian:
                l.reverse()
            packer.result.extend(l)
        packer.args_index += repetitions
    return pack_float


text:
import axios from 'axios';
import Promise from 'bluebird';
import Transport from 'vfs/transport';
import FileMetadata from 'vfs/file';
import FileDataURL from 'vfs/filedataurl';
import MountManager from 'core/mount-manager';
import {_} from 'core/locales';
import * as GoogleAPI from 'helpers/google-api';
import * as FS from 'utils/fs';

const CACHE_CLEAR_TIMEOUT = 7000;

let gapi = window.gapi = window.gapi || {};
let _authenticated;
let _clearCacheTimeout;
let _rootFolderId;
let _treeCache;

/*
 * Generate FileView compatible array of scandir()
 */
function createDirectoryList(dir, list, item, options, match) {
  const result = [];
  const rdir = dir.replace(match, '/').replace(/\/+/g, '/');
  const isOnRoot = rdir === '/';

  function createItem(iter, i) {
    let path = dir;
    if ( iter.title === '..' ) {
      path = FS.dirname(dir);
    } else {
      if ( !isOnRoot ) {
        path += '/';
      }
      path += iter.title;
    }
    let fileType = iter.mimeType === 'application/vnd.google-apps.folder' ? 'dir' : (iter.kind === 'drive#file' ? 'file' : 'dir');
    if ( iter.mimeType === 'application/vnd.google-apps.trash' ) {
      fileType = 'trash';
    }

    return new FileMetadata({
      filename: iter.title,
      path: path,
      id: iter.id,
      size: iter.quotaBytesUsed || 0,
      mime: iter.mimeType === 'application/vnd.google-apps.folder' ? null : iter.mimeType,
      type: fileType
    });
  }

  if ( list ) {
    list.forEach((iter, i) => {
      if ( !iter ) {
        return;
      }
      result.push(createItem(iter, i));
    });
  }
  return result ? result : [];
}

/*
 * Get all files in a directory
 */
function getAllDirectoryFiles(item, callback) {
  console.debug('GoogleDrive::*getAllDirectoryFiles()', item);

  function retrieveAllFiles(cb) {
    if ( _clearCacheTimeout ) {
      clearTimeout(_clearCacheTimeout);
      _clearCacheTimeout = null;
    }
    if ( _treeCache ) {
      console.info('USING CACHE FROM PREVIOUS FETCH!');
      cb(false, _treeCache);
      return;
    }
    console.info('UPDATING CACHE');

    let list = [];

    function retrievePageOfFiles(request, result) {
      request.execute((resp) => {
        if ( resp.error ) {
          console.warn('GoogleDrive::getAllDirectoryFiles()', 'error', resp);
        }

        result = result.concat(resp.items);

        const nextPageToken = resp.nextPageToken;
        if (nextPageToken) {
          request = gapi.client.drive.files.list({
            pageToken: nextPageToken
          });
          retrievePageOfFiles(request, result);
        } else {
          _treeCache = result;

          cb(false, result);
        }
      });
    }

    try {
      const initialRequest = gapi.client.drive.files.list({});
      retrievePageOfFiles(initialRequest, list);
    } catch ( e ) {
      console.warn('GoogleDrive::getAllDirectoryFiles() exception', e, e.stack);
      console.warn('THIS ERROR OCCURS WHEN MULTIPLE REQUESTS FIRE AT ONCE ?!'); // FIXME
      cb(false, list);
    }
  }

  function getFilesBelongingTo(list, root, cb) {
    const idList = {};
    const parentList = {};
    list.forEach((iter) => {
      if ( iter ) {
        idList[iter.id] = iter;
        const parents = [];
        if ( iter.parents ) {
          iter.parents.forEach((piter) => {
            if ( piter ) {
              parents.push(piter.id);
            }
          });
        }
        parentList[iter.id] = parents;
      }
    });

    let resolves = FS.getPathFromVirtual(root).replace(/^\/+/, '').split('/');
    resolves = resolves.filter((el) => {
      return el !== '';
    });

    let currentParentId = _rootFolderId;
    let isOnRoot = !resolves.length;

    function _getFileList(foundId) {
      const result = [];

      if ( !isOnRoot ) {
        result.push({
          title: '..',
          path: FS.dirname(root),
          id: item.id,
          quotaBytesUsed: 0,
          mimeType: 'application/vnd.google-apps.folder'
        });
      }

      list.forEach((iter) => {
        if ( iter && parentList[iter.id] && parentList[iter.id].indexOf(foundId) !== -1 ) {
          result.push(iter);
        }
      });
      return result;
    }

    function _nextDir(completed) {
      let current = resolves.shift();
      let done = resolves.length <= 0;
      let found;

      if ( isOnRoot ) {
        found = currentParentId;
      } else {
        if ( current ) {
          list.forEach((iter) => {
            if ( iter ) {
              if ( iter.title === current && parentList[iter.id] && parentList[iter.id].indexOf(currentParentId) !== -1 ) {
                currentParentId = iter.id;
                found  = iter.id;
              }
            }
          });
        }
      }

      if ( done ) {
        completed(found);
      } else {
        _nextDir(completed);
      }
    }

    _nextDir((foundId) => {
      if ( foundId && idList[foundId] ) {
        cb(false, _getFileList(foundId));
        return;
      } else {
        if ( isOnRoot ) {
          cb(false, _getFileList(currentParentId));
          return;
        }
      }

      cb('Could not list directory');
    });
  }

  function doRetrieve() {
    retrieveAllFiles((error, list) => {
      const root = item.path;
      if ( error ) {
        callback(error, false, root);
        return;
      }

      getFilesBelongingTo(list, root, (error, response) => {
        console.groupEnd();

        _clearCacheTimeout = setTimeout(() => {
          console.info('Clearing GoogleDrive filetree cache!');
          _treeCache = null;
        }, CACHE_CLEAR_TIMEOUT);

        console.debug('GoogleDrive::*getAllDirectoryFiles()', '=>', response);
        callback(error, response, root);
      });
    });

  }

  console.group('GoogleDrive::*getAllDirectoryFiles()');

  if ( !_rootFolderId ) {
    const request = gapi.client.drive.about.get();
    request.execute((resp) => {
      if ( !resp || !resp.rootFolderId ) {
        callback(_('ERR_VFSMODULE_ROOT_ID'));
        return;
      }
      _rootFolderId = resp.rootFolderId;

      doRetrieve();
    });
  } else {
    doRetrieve();
  }

}

/*
 * Scans entire file tree for given path
 */
function getFileFromPath(dir, type, callback) {
  if ( dir instanceof FileMetadata ) {
    dir = dir.path;
  }

  const tmpItem = new FileMetadata({
    filename: FS.filename(dir),
    type: 'dir',
    path: FS.dirname(dir)
  });

  console.debug('GoogleDrive::*getFileIdFromPath()', dir, type, tmpItem);

  getAllDirectoryFiles(tmpItem, (error, list, ldir) => {
    if ( error ) {
      callback(error);
      return;
    }

    let found = null;
    list.forEach((iter) => {
      if ( iter.title === FS.filename(dir) ) {
        if ( type ) {
          if ( iter.mimeType === type ) {
            found = iter;
            return false;
          }
        } else {
          found = iter;
        }
      }
      return true;
    });

    callback(false, found);
  });
}

/*
 * Gets the parent path
 */
function getParentPathId(item, callback) {
  const dir = FS.dirname(item.path);
  const type = 'application/vnd.google-apps.folder';

  console.debug('GoogleDrive::*getParentPathId()', item);

  getFileFromPath(dir, type, (error, item) => {
    if ( error ) {
      callback(error);
    } else {
      callback(false, item ? item.id : null);
    }
  });
}

/*
 * Creates the boundary data for uploads
 */
function createBoundary(file, data, callback) {
  const boundary = '-------314159265358979323846';
  const delimiter = '\r\n--' + boundary + '\r\n';
  const close_delim = '\r\n--' + boundary + '--';
  const contentType = file.mime || 'text/plain'; //fileData.type || 'application/octet-stream';

  function createBody(result) {
    const metadata = {
      title: file.filename,
      mimeType: contentType
    };
    const base64Data = result;
    const multipartRequestBody =
        delimiter +
        'Content-Type: application/json\r\n\r\n' +
        JSON.stringify(metadata) +
        delimiter +
        'Content-Type: ' + contentType + '\r\n' +
        'Content-Transfer-Encoding: base64\r\n' +
        '\r\n' +
        base64Data +
        close_delim;

    return multipartRequestBody;
  }

  const reqContentType = 'multipart/mixed; boundary=\'' + boundary + '\'';

  if ( data instanceof FileDataURL ) {
    callback(false, {
      contentType: reqContentType,
      body: createBody(data.toBase64())
    });
  } else {
    FS.abToBinaryString(data, contentType, (error, response) => {
      callback(error, error ? false : {
        contentType: reqContentType,
        body: createBody(btoa(response))
      });
    });
  }
}

/*
 * Sets the folder for a file
 */
function setFolder(item, pid, callback) {
  console.info('GoogleDrive::setFolder()', item, pid);

  pid = pid || 'root';

  function _clearFolders(cb) {
    item.parents.forEach((p, i) => {
      const request = gapi.client.drive.children.delete({
        folderId: p.id,
        childId: item.id
      });

      request.execute((resp) => {
        if ( i >= (item.parents.length - 1) ) {
          cb();
        }
      });
    });
  }

  function _setFolder(rootId, cb) {
    const request = gapi.client.drive.children.insert({
      folderId: pid,
      resource: {id: item.id}
    });

    request.execute((resp) => {
      console.info('GoogleDrive::setFolder()', '=>', resp);
      callback(false, true);
    });
  }

  _clearFolders(() => {
    _setFolder(pid, callback);
  });
}

///////////////////////////////////////////////////////////////////////////////
// TRANSPORTER
///////////////////////////////////////////////////////////////////////////////

/**
 * Google Drive VFS Transport Module
 *
 * @extends Transport
 */
export default class GoogleDriveTransport extends Transport {

  _init() {
    if ( _authenticated ) {
      return Promise.resolve();
    }

    return new Promise((resolve, reject) => {
      GoogleAPI.create({
        scope: [
          'https://www.googleapis.com/auth/drive.install',
          'https://www.googleapis.com/auth/drive.file',
          'openid'
        ],
        load: [
          'drive-realtime',
          'drive-share'
        ]
      }, (err, res) => {
        gapi.client.load('drive', 'v2', (err) => {
          if ( !err ) {
            _authenticated = true;
          }

          return err ? reject(new Error(err)) : resolve(true);
        });
      });
    });
  }

  request(method, args, options, mount) {
    const fargs = arguments;
    return new Promise((resolve, reject) => {
      this._init().then(() => {
        return super.request(...fargs).then(resolve).catch(reject);
      }).catch(reject);
    });
  }

  scandir(item, options, mount) {
    return new Promise((resolve, reject) => {
      getAllDirectoryFiles(item, (error, list, dir) => {
        if ( error ) {
          reject(new Error(error));
        } else {
          const result = createDirectoryList(dir, list, item, options, mount.option('match'));
          resolve(result);
        }
      });
    });
  }

  read(item, options, mount) {
    const read = (ritem) => new Promise((resolve, reject) => {

      const request = gapi.client.drive.files.get({
        fileId: ritem.id
      });

      request.execute((file) => {

        if ( file && file.id ) {
          let accessToken = gapi.auth.getToken().access_token;

          axios({
            url: file.downloadUrl,
            method: 'GET',
            responseType: 'arraybuffer',
            headers: {'Authorization': 'Bearer ' + accessToken}
          }).then((response) => {
            return resolve(response.data);
          }).catch((error) => {
            reject(new Error(_('ERR_VFSMODULE_XHR_ERROR') + ' - ' + error.message));
          });
        } else {
          reject(new Error(_('ERR_VFSMODULE_NOSUCH')));
        }
      });
    });

    return new Promise((resolve, reject) => {
      if ( item.downloadUrl ) {
        read(item).then(resolve).catch(reject);
      } else {
        getFileFromPath(item.path, item.mime, function(error, response) {
          if ( error ) {
            reject(new Error(error));
          } else if ( !response ) {
            reject(new Error(_('ERR_VFSMODULE_NOSUCH')));
          } else {
            read(response).then(resolve).catch(reject);
          }
        });
      }
    });
  }

  write(file, data) {
    const write = (parentId, fileId) => new Promise((resolve, reject) => {
      let uri = '/upload/drive/v2/files';
      let method = 'POST';
      if ( fileId ) {
        uri = '/upload/drive/v2/files/' + fileId;
        method = 'PUT';
      }

      createBoundary(file, data, (error, fileData) => {
        if ( error ) {
          reject(new Error(error));
        } else {
          const request = gapi.client.request({
            path: uri,
            method: method,
            params: {uploadType: 'multipart'},
            headers: {'Content-Type': fileData.contentType},
            body: fileData.body
          });

          request.execute((resp) => {
            _treeCache = null; // Make sure we refetch any cached stuff

            if ( resp && resp.id ) {
              if ( parentId ) {
                setFolder(resp, parentId, (err, res) => {
                  return err ? reject(new Error(err)) : resolve(res);
                });
              } else {
                resolve(true);
              }
            } else {
              reject(_('ERR_VFSMODULE_NOSUCH'));
            }
          });
        }
      });
    });

    return new Promise((resolve, reject) => {
      getParentPathId(file, (error, id) => {
        if ( error ) {
          reject(new Error(error));
        } else if ( file.id ) {
          write(id, file.id).then(resolve).catch(reject);
        } else {
          this.exists(file).then((exists) => {
            return write(id, exists ? exists.id : null).then(resolve).catch(reject);
          }).catch(() => {
            write(id, null).then(resolve).catch(reject);
          });
        }
      });
    });
  }

  copy(src, dest) {
    return new Promise((resolve, reject) => {
      const request = gapi.client.drive.files.copy({
        fileId: src.id, //FS.filename(src.path),
        resource: {title: FS.filename(dest.path)}
      });

      request.execute((resp) => {
        if ( resp.id ) {
          getParentPathId(dest, (error, parentId) => {
            if ( error ) {
              console.warn(error);
              resolve(true);
            } else {
              _treeCache = null; // Make sure we refetch any cached stuff

              setFolder(resp, parentId, (err, res) => {
                return err ? reject(new Error(err)) : resolve(res);
              });
            }
          });
        } else {
          const msg = resp && resp.message ? resp.message : _('ERR_APP_UNKNOWN_ERROR');
          reject(new Error(msg));
        }
      });
    });
  }

  move(src, dest) {
    return new Promise((resolve, reject) => {
      const request = gapi.client.drive.files.patch({
        fileId: src.id,
        resource: {
          title: FS.filename(dest.path)
        }
      });

      request.execute((resp) => {
        if ( resp && resp.id ) {
          _treeCache = null; // Make sure we refetch any cached stuff

          resolve(true);
        } else {
          const msg = resp && resp.message ? resp.message : _('ERR_APP_UNKNOWN_ERROR');
          reject(new Error(msg));
        }
      });
    });
  }

  exists(item) {
    // FIXME Is there a better way to do this ?
    return new Promise((resolve, reject) => {
      const req = new FileMetadata(FS.dirname(item.path));
      this.scandir(req).then((result) => {
        const found = result.find((iter) => iter.path === item.path);
        if ( found ) {
          const file = new FileMetadata(item.path, found.mimeType);
          file.id = found.id;
          file.title = found.title;
          return resolve(file);
        }

        return resolve(false);
      }).catch(reject);
    });
  }

  fileinfo(item) {
    return new Promise((resolve, reject) => {
      const request = gapi.client.drive.files.get({
        fileId: item.id
      });

      request.execute((resp) => {
        if ( resp && resp.id ) {
          const useKeys = ['createdDate', 'id', 'lastModifyingUser', 'lastViewedByMeDate', 'markedViewedByMeDate', 'mimeType', 'modifiedByMeDate', 'modifiedDate', 'title', 'alternateLink'];
          const info = {};
          useKeys.forEach((k) => {
            info[k] = resp[k];
          });

          resolve(info);
        } else {
          reject(_('ERR_VFSMODULE_NOSUCH'));
        }
      });
    });
  }

  url(item) {
    return new Promise((resolve, reject) => {
      if ( !item || !item.id ) {
        reject(new Error('url() expects a File ref with Id'));
      } else {
        const request = gapi.client.drive.files.get({
          fileId: item.id
        });

        request.execute((resp) => {
          if ( resp && resp.webContentLink ) {
            resolve(resp.webContentLink);
          } else {
            const msg = resp && resp.message ? resp.message : _('ERR_APP_UNKNOWN_ERROR');
            reject(new Error(msg));
          }
        });
      }
    });
  }

  mkdir(dir) {
    const mkdir = (parents) => new Promise((resolve, reject) => {
      const request = gapi.client.request({
        'path': '/drive/v2/files',
        'method': 'POST',
        'body': JSON.stringify({
          title: dir.filename,
          parents: parents,
          mimeType: 'application/vnd.google-apps.folder'
        })
      });

      request.execute((resp) => {
        if ( resp && resp.id ) {
          _treeCache = null; // Make sure we refetch any cached stuff
          resolve(true);
        } else {
          const msg = resp && resp.message ? resp.message : _('ERR_APP_UNKNOWN_ERROR');
          reject(new Error(msg));
        }
      });
    });

    return new Promise((resolve, reject) => {
      const module = MountManager.getModuleFromPath(dir.path);
      const dirDest = FS.getPathFromVirtual(FS.dirname(dir.path));
      const rootDest = FS.getPathFromVirtual(module.option('root'));

      if ( dirDest !== rootDest ) {
        getParentPathId(dir, (error, id) => {
          if ( error || !id ) {
            reject(new Error(_('ERR_VFSMODULE_PARENT_FMT', error || _('ERR_VFSMODULE_PARENT'))));
          } else {
            mkdir([{id: id}]).then(resolve).catch(reject);
          }
        });
      } else {
        mkdir(null).then(resolve).catch(reject);
      }
    });
  }

  upload(dest, file) {
    const item = new FileMetadata({
      filename: file.name,
      path: FS.pathJoin(dest.path, file.name),
      mime: file.type,
      size: file.size
    });

    return this.write(item, file);
  }

  trash(file) {
    return new Promise((resolve, reject) => {
      const request = gapi.client.drive.files.trash({
        fileId: file.id
      });

      request.execute((resp) => {
        if ( resp.id ) {
          resolve(true);
        } else {
          const msg = resp && resp.message ? resp.message : _('ERR_APP_UNKNOWN_ERROR');
          reject(new Error(msg));
        }
      });
    });
  }

  untrash(file) {
    return new Promise((resolve, reject) => {
      const request = gapi.client.drive.files.untrash({
        fileId: file.id
      });

      request.execute((resp) => {
        if ( resp.id ) {
          resolve(true);
        } else {
          const msg = resp && resp.message ? resp.message : _('ERR_APP_UNKNOWN_ERROR');
          reject(new Error(msg));
        }
      });
    });
  }

  emptyTrash() {
    return new Promise((resolve, reject) => {
      const request = gapi.client.drive.files.emptyTrash({});
      request.execute((resp) => {
        if ( resp && resp.message ) {
          const msg = resp && resp.message ? resp.message : _('ERR_APP_UNKNOWN_ERROR');
          reject(new Error(msg));
        } else {
          resolve(true);
        }
      });
    });
  }

  freeSpace(root) {
    return Promise.resolve(-1);
  }

  unlink(src) {
    const unlink = (s) => {
      _treeCache = null; // Make sure we refetch any cached stuff

      return new Promise((resolve, reject) => {
        const request = gapi.client.drive.files.delete({
          fileId: s.id
        });

        request.execute((resp) => {
          if ( resp && (typeof resp.result === 'object') ) {
            resolve(true);
          } else {
            const msg = resp && resp.message ? resp.message : _('ERR_APP_UNKNOWN_ERROR');
            reject(new Error(msg));
          }
        });
      });
    };

    if ( !src.id ) {
      return new Promise((resolve, reject) => {
        getFileFromPath(src.path, src.mime, (error, response) => {
          if ( error ) {
            reject(new Error(error));
          } else if ( !response ) {
            reject(new Error(_('ERR_VFSMODULE_NOSUCH')));
          } else {
            unlink(response).then(resolve).catch(reject);
          }
        });
      });
    }

    return unlink(src);
  }

}


text:
"""
Example of a Gamma distribution
-------------------------------
Figure 3.18.

This shows an example of a gamma distribution with various parameters.
We'll generate the distribution using::

    dist = scipy.stats.gamma(...)

Where ... should be filled in with the desired distribution parameters
Once we have defined the distribution parameters in this way, these
distribution objects have many useful methods; for example:

* ``dist.pmf(x)`` computes the Probability Mass Function at values ``x``
  in the case of discrete distributions

* ``dist.pdf(x)`` computes the Probability Density Function at values ``x``
  in the case of continuous distributions

* ``dist.rvs(N)`` computes ``N`` random variables distributed according
  to the given distribution

Many further options exist; refer to the documentation of ``scipy.stats``
for more details.
"""
# Author: Jake VanderPlas
# License: BSD
#   The figure produced by this code is published in the textbook
#   "Statistics, Data Mining, and Machine Learning in Astronomy" (2013)
#   For more information, see http://astroML.github.com
#   To report a bug or issue, use the following forum:
#    https://groups.google.com/forum/#!forum/astroml-general
import numpy as np
from scipy.stats import gamma
from matplotlib import pyplot as plt

#----------------------------------------------------------------------
# This function adjusts matplotlib settings for a uniform feel in the textbook.
# Note that with usetex=True, fonts are rendered with LaTeX.  This may
# result in an error if LaTeX is not installed on your system.  In that case,
# you can set usetex to False.
from astroML.plotting import setup_text_plots
setup_text_plots(fontsize=8, usetex=True)

#------------------------------------------------------------
# plot the distributions
k_values = [1, 2, 3, 5]
theta_values = [2, 1, 1, 0.5]
linestyles = ['-', '--', ':', '-.']
x = np.linspace(1E-6, 10, 1000)

#------------------------------------------------------------
# plot the distributions
fig, ax = plt.subplots(figsize=(5, 3.75))

for k, t, ls in zip(k_values, theta_values, linestyles):
    dist = gamma(k, 0, t)
    plt.plot(x, dist.pdf(x), ls=ls, c='black',
             label=r'$k=%.1f,\ \theta=%.1f$' % (k, t))

plt.xlim(0, 10)
plt.ylim(0, 0.45)

plt.xlabel('$x$')
plt.ylabel(r'$p(x|k,\theta)$')
plt.title('Gamma Distribution')

plt.legend(loc=0)
plt.show()