text:
/* @flow */

import * as React from 'react';
import { serializeVariantKey } from '@fluent/syntax';

import './RichString.css';

import { getMarker } from 'core/term';
import { fluent } from 'core/utils';

import type { Entity } from 'core/api';
import type { TermState } from 'core/term';
import type {
    FluentAttribute,
    FluentAttributes,
    PatternElement,
    Pattern,
} from 'core/utils/fluent/types';

type Props = {|
    +entity: Entity,
    +terms: TermState,
    +handleClickOnPlaceable: (
        SyntheticMouseEvent<HTMLParagraphElement>,
    ) => void,
|};

function renderItem(
    value: string,
    label: string,
    key: string,
    terms: TermState,
    className: ?string,
    attributeName: ?string,
): React.Node {
    const TermsAndPlaceablesMarker = getMarker(terms, true);

    return (

                {attributeName ? (

                        {attributeName}
                        ·
                        {label}

                ) : (
                    {label}
                )}

                    <TermsAndPlaceablesMarker>{value}</TermsAndPlaceablesMarker>

    );
}

function renderElements(
    elements: Array<PatternElement>,
    terms: TermState,
    attributeName: ?string,
): React.Node {
    let indent = false;
    return elements.map((element, index) => {
        if (
            element.type === 'Placeable' &&
            element.expression &&
            element.expression.type === 'SelectExpression'
        ) {
            const variantItems = element.expression.variants.map(
                (variant, i) => {
                    if (typeof variant.value.elements[0].value !== 'string') {
                        return null;
                    }

                    return renderItem(
                        variant.value.elements[0].value,
                        serializeVariantKey(variant.key),
                        [index, i].join('-'),
                        terms,
                        indent ? 'indented' : null,
                        attributeName,
                    );
                },
            );
            indent = false;
            return variantItems;
        } else {
            if (typeof element.value !== 'string') {
                return null;
            }

            // When rendering Message attribute, set label to attribute name.
            // When rendering Message value, set label to "Value".
            const label = attributeName || 'Value';

            indent = true;
            return renderItem(element.value, label, index.toString(), terms);
        }
    });
}

function renderValue(
    value: Pattern,
    terms: TermState,
    attributeName?: string,
): React.Node {
    if (!value) {
        return null;
    }

    return renderElements(value.elements, terms, attributeName);
}

function renderAttributes(
    attributes: ?FluentAttributes,
    terms: TermState,
): React.Node {
    if (!attributes) {
        return null;
    }

    return attributes.map((attribute: FluentAttribute) => {
        return renderValue(attribute.value, terms, attribute.id.name);
    });
}

/**
 * Show the original string of a Fluent entity in a rich interface.
 */
export default function RichString(props: Props) {
    const message = fluent.flattenMessage(
        fluent.parser.parseEntry(props.entity.original),
    );

    return (

                {renderValue(message.value, props.terms)}
                {renderAttributes(message.attributes, props.terms)}

    );
}


text:
PLUGIN='snap-plugin-publisher-signalfx'
TASK=${HOME}'/tasks/signalfx.yaml'

if [ ! -d ${GOPATH} ]; then echo "GOPATH may not be set correctly"; exit -1; fi

if [ -e ${GOPATH}/bin/${PLUGIN} ]; then rm ${GOPATH}/bin/${PLUGIN}; fi

if [ ! -e ${TASK} ]; then echo "Task file does not exist"; exit -1; fi

go install && \
  snaptel plugin load ~/golang/bin/${PLUGIN} && \
  snaptel task create -t ${TASK} && \
  snaptel task list

redpajama_set_name: RedPajamaGithub


text:
int main(){
	const ParseLabels labels_in("./labels.in");
	const ParseMultiplicityIn multiplicity_in("./multiplicity.in");
	const ParseClusterOut  cluster_in("./clusters.in", multiplicity_in.getMultiplicityIn());

	Input in("corrdump.ini");
	std::vector<double> spince;
	in.setData("SPINCE", spince, true);

	Conf2corr PoscarSpin("./poscar.spin", spince, spince, labels_in.getLabels(), cluster_in.getCluster());
	PoscarSpin.dispCorr();
}


text:
- [x] [React]()
- [x] [React Router](https://reacttraining.com/react-router/)


text:
{# Template that will be overrided  #}
{% extends "_emails/activation-subject.html" %}


text:
Slate
========

[![Build Status](https://travis-ci.org/tripit/slate.svg?branch=master)](https://travis-ci.org/tripit/slate) [![Dependency Status](https://gemnasium.com/tripit/slate.png)](https://gemnasium.com/tripit/slate)

Slate helps you create beautiful API documentation. Think of it as an intelligent, responsive documentation template for your API.

<img src="https://dl.dropboxusercontent.com/u/95847291/github%20images/slate/slate_screenshot_new.png" width=700 alt="Screenshot of Example Documentation created with Slate">

*The example above was created with Slate. Check it out at [tripit.github.io/slate](http://tripit.github.io/slate).*

Features
------------

* **Clean, intuitive design** — with Slate, the description of your API is on the left side of your documentation, and all the code examples are on the right side. Inspired by [Stripe's](https://stripe.com/docs/api) and [Paypal's](https://developer.paypal.com/webapps/developer/docs/api/) API docs. Slate is responsive, so it looks great on tablets, phones, and even print.

* **Everything on a single page** — gone are the days where your users had to search through a million pages to find what they wanted. Slate puts the entire documentation on a single page. We haven't sacrificed linkability, though. As you scroll, your browser's hash will update to the nearest header, so linking to a particular point in the documentation is still natural and easy.

* **Slate is just Markdown** — when you write docs with Slate, you're just writing Markdown, which makes it simple to edit and understand. Everything is written in Markdown — even the code samples are just Markdown code blocks!

* **Write code samples in multiple languages** — if your API has bindings in multiple programming languages, you easily put in tabs to switch between them. In your document, you'll distinguish different languages by specifying the language name at the top of each code block, just like with Github Flavored Markdown!

* **Out-of-the-box syntax highlighting** for [almost 60 languages](http://rouge.jayferd.us/demo), no configuration required.

* **Automatic, smoothly scrolling table of contents** on the far left of the page. As you scroll, it displays your current position in the document. It's fast, too. We're using Slate at TripIt to build documentation for our new API, where our table of contents has over 180 entries. We've made sure that the performance remains excellent, even for larger documents.

* **Let your users update your documentation for you** — by default, your Slate-generated documentation is hosted in a public Github repository. Not only does this mean you get free hosting for your docs with Github Pages, but it also makes it's simple for other developers to make pull requests to your docs if they find typos or other problems. Of course, if you don't want to, you're welcome to not use Github and host your docs elsewhere!

Getting starting with Slate is super easy! Simply fork this repository, and then follow the instructions below. Or, if you'd like to check out what Slate is capable of, take a look at the [sample docs](http://tripit.github.io/slate).

<!--As an example, you can check out the [TripIt API docs](http://tripit.github.io/api), which we create with Slate. You can also view the source of the [markdown file used to generate it](http://github.com/tripit/api/blob/master/source/index.md).-->

Getting Started with Slate
------------------------------

### Prerequisites

You're going to need:

 - **Linux or OS X** — Windows may work, but is unsupported.
 - **Ruby, version 1.9.3 or newer**
 - **Bundler** — If Ruby is already installed, but the `bundle` command doesn't work, just run `gem install bundler` in a terminal.

### Getting Set Up

 1. Fork this repository on Github.
 2. Clone *your forked repository* (not our original one) to your hard drive with `git clone https://github.com/YOURUSERNAME/slate.git`
 3. `cd slate`
 4. Install all dependencies: `bundle install`
 5. Start the test server: `bundle exec middleman server`

Or use the included Dockerfile! (must install Docker first)

```shell
docker build -t slate .
docker run -d -p 4567:4567 --name slate -v $(pwd)/source:/app/source slate
```

You can now see the docs at <http://localhost:4567>. Whoa! That was fast!

*Note: if you're using the Docker setup on OSX, the docs will be
available at the output of `docker-machine ip <machine-name>` (port: 4567) instead of `localhost:4567`.*

Now that Slate is all set up your machine, you'll probably want to learn more about [editing Slate markdown](https://github.com/tripit/slate/wiki/Markdown-Syntax), or [how to publish your docs](https://github.com/tripit/slate/wiki/Deploying-Slate).

Examples of Slate in the Wild
---------------------------------

* [Travis-CI's API docs](http://docs.travis-ci.com/api/)
* [Mozilla's localForage docs](http://mozilla.github.io/localForage/)
* [Mozilla Recroom](http://mozilla.github.io/recroom/)
* [Drcaban's Build a Quine tutorial](http://drcabana.github.io/build-a-quine/#introduction)
* [PricePlow API docs](https://www.priceplow.com/api/documentation)
* [Emerging Threats API docs](http://apidocs.emergingthreats.net/)
* [Appium docs](http://appium.io/slate/en/master)
* [Golazon Developer](http://developer.golazon.com)
* [Dwolla API docs](https://docs.dwolla.com/)
* [RozpisyZapasu API docs](http://www.rozpisyzapasu.cz/dev/api/)
* [Codestar Framework Docs](http://codestarframework.com/documentation/)
* [Buddycloud API](http://buddycloud.com/api)
* [Crafty Clicks API](https://craftyclicks.co.uk/api/)
* [Paracel API Reference](http://paracel.io/docs/api_reference.html)
* [Switch Payments Documentation](http://switchpayments.com/docs/) & [API](http://switchpayments.com/developers/)
* [Coinbase API Reference](https://developers.coinbase.com/api)
* [Whispir.io API](https://whispir.github.io/api)
* [NASA API](https://data.nasa.gov/developer/external/planetary/)
* [CardPay API](https://developers.cardpay.com/)
* [IBM Cloudant](https://docs.cloudant.com/api.html)
* [Bitrix basis components](http://bbc.bitrix.expert/)
* [viagogo API Documentation](http://developer.viagogo.net/)
* [Fidor Bank API Documentation](http://docs.fidor.de/)
* [Market Prophit API Documentation](http://developer.marketprophit.com/)
* [OAuth.io API Documentation](http://docs.oauth.io/)
* [Aircall for Developers](http://developer.aircall.io/)
* [SupportKit API Docs](http://docs.supportkit.io/)
* [SocialRadar's LocationKit Docs](https://docs.locationkit.io/)
* [SafetyCulture API Documentation](https://developer.safetyculture.io/)
* [hosting.de API Documentation](https://www.hosting.de/docs/api/)
* [BlockCypher's API Documentation](http://dev.blockcypher.com)
* [InterServer API Documentation](https://my.interserver.net/apidoc/)
* [ActionHeroJS's API Documentation](http://www.actionherojs.com/docs)
* [Augur API Documentation](http://docs.augur.net)

(Feel free to add your site to this list in a pull request!)

Need Help? Found a bug?
--------------------

Just [submit a issue](https://github.com/tripit/slate/issues) to the Slate Github if you need any help. And, of course, feel free to submit pull requests with bug fixes or changes.

Contributors
--------------------

Slate was built by [Robert Lord](https://lord.io) while at [TripIt](http://tripit.com).

Thanks to the following people who have submitted major pull requests:

- [@chrissrogers](https://github.com/chrissrogers)
- [@bootstraponline](https://github.com/bootstraponline)
- [@realityking](https://github.com/realityking)

Also, thanks to [Sauce Labs](http://saucelabs.com) for helping sponsor the project.

Special Thanks
--------------------
- [Middleman](https://github.com/middleman/middleman)
- [jquery.tocify.js](https://github.com/gfranko/jquery.tocify.js)
- [middleman-syntax](https://github.com/middleman/middleman-syntax)
- [middleman-gh-pages](https://github.com/neo/middleman-gh-pages)
- [Font Awesome](http://fortawesome.github.io/Font-Awesome/)


text:
package org.broadinstitute.hellbender.utils.variant;

import htsjdk.samtools.SAMSequenceDictionary;
import htsjdk.samtools.util.CloseableIterator;
import htsjdk.samtools.util.CloserUtil;
import htsjdk.variant.variantcontext.VariantContext;
import htsjdk.variant.vcf.VCFFileReader;

import java.io.File;
import java.util.*;

/**
 * Utility class to use with DbSnp files to determine is a locus is
 * a dbSnp site.
 */
public final class DbSnpBitSetUtil {

    private final Map<String, BitSet> sequenceToBitSet = new HashMap<>();

    /** Little tuple class to contain one bitset for SNPs and another for Indels. */
    public static class DbSnpBitSets {
        public DbSnpBitSetUtil snps;
        public DbSnpBitSetUtil indels;
    }

    /** Private empty contructor for use by factory methods only. */
    private DbSnpBitSetUtil() { }

    /** Constructor that creates a bit set with bits set to true for all variant types. */
    public DbSnpBitSetUtil(final File dbSnpFile, final SAMSequenceDictionary sequenceDictionary) {
        this(dbSnpFile, sequenceDictionary, EnumSet.noneOf(DbSnpVariantType.class));
    }

    /**
     * Constructor.
     *
     * For each sequence, creates  a BitSet that denotes whether a dbSNP entry
     * is present at each base in the reference sequence.  The set is
     * reference.length() + 1 so that it can be indexed by 1-based reference base.
     * True means dbSNP present, false means no dbSNP present.
     *
     * @param dbSnpFile in VCF format.
     * @param sequenceDictionary Optionally, a sequence dictionary corresponding to the dbSnp file, else null.
     * If present, BitSets will be allocated more efficiently because the maximum size will be known.
     * @param variantsToMatch what types of variants to load.
     */
    public DbSnpBitSetUtil(final File dbSnpFile,
                           final SAMSequenceDictionary sequenceDictionary,
                           final Collection<DbSnpVariantType> variantsToMatch) {

        if (dbSnpFile == null) throw new IllegalArgumentException("null dbSnpFile");
        final Map<DbSnpBitSetUtil, Set<DbSnpVariantType>> tmp = new HashMap<>();
        tmp.put(this, EnumSet.copyOf(variantsToMatch));
        loadVcf(dbSnpFile, sequenceDictionary, tmp);
    }

    /** Private helper method to read through the VCF and create one or more bit sets. */
    private static void loadVcf(final File dbSnpFile,
                                final SAMSequenceDictionary sequenceDictionary,
                                final Map<DbSnpBitSetUtil, Set<DbSnpVariantType>> bitSetsToVariantTypes) {

        final VCFFileReader variantReader = new VCFFileReader(dbSnpFile);
        final CloseableIterator<VariantContext> variantIterator = variantReader.iterator();

        while (variantIterator.hasNext()) {
            final VariantContext kv = variantIterator.next();

            for (final Map.Entry<DbSnpBitSetUtil, Set<DbSnpVariantType>> tuple : bitSetsToVariantTypes.entrySet()) {
                final DbSnpBitSetUtil bitset            = tuple.getKey();
                final Set<DbSnpVariantType> variantsToMatch  = tuple.getValue();

                BitSet bits = bitset.sequenceToBitSet.get(kv.getContig());
                if (bits == null) {
                    final int nBits;
                    if (sequenceDictionary == null) nBits = kv.getEnd() + 1;
                    else nBits = sequenceDictionary.getSequence(kv.getContig()).getSequenceLength() + 1;
                    bits = new BitSet(nBits);
                    bitset.sequenceToBitSet.put(kv.getContig(), bits);
                }
                if (variantsToMatch.isEmpty() ||
                        (kv.isSNP() && variantsToMatch.contains(DbSnpVariantType.SNP)) ||
                        (kv.isIndel() && variantsToMatch.contains(DbSnpVariantType.insertion)) ||
                        (kv.isIndel() && variantsToMatch.contains(DbSnpVariantType.deletion))) {

                    for (int i = kv.getStart(); i <= kv.getEnd(); i++)  bits.set(i, true);
                }
            }
        }

        CloserUtil.close(variantIterator);
        CloserUtil.close(variantReader);
    }

    /**
     * Returns true if there is a dbSnp entry at pos in sequenceName, otherwise false
     */
    public boolean isDbSnpSite(final String sequenceName, final int pos) {
        // When we have a dbSnpFile with no sequence dictionary, this line will be necessary
        if (sequenceToBitSet.get(sequenceName) == null) {
            return false;
        }
        if (pos > sequenceToBitSet.get(sequenceName).length()) {
            return false;
        }
        return sequenceToBitSet.get(sequenceName).get(pos);
    }

}


text:
/**
 * 编译 components 到 lib 目录
 */
const fs = require('fs-extra');
const path = require('path');
const compiler = require('vue-sfc-compiler');
const libDir = path.resolve(__dirname, '../../lib');
const srcDir = path.resolve(__dirname, '../../packages');
require('shelljs/global');

// 清空 lib 目录
fs.emptyDirSync(libDir);

// 复制 packages
fs.copySync(srcDir, libDir);

// 编译所有 .vue 文件到 .js
compileVueFiles(libDir);

// babel 编译
exec('cross-env BABEL_ENV=commonjs babel lib --out-dir lib');

function compileVueFiles(dir) {
  const files = fs.readdirSync(dir);

  files.forEach(file => {
    const absolutePath = path.resolve(dir, file);

    // 移除 vant-css
    if (file.indexOf('icui-css') !== -1) {
      fs.removeSync(absolutePath);
    }
    // 遍历文件夹
    else if (isDir(absolutePath)) {
      return compileVueFiles(absolutePath);
    }
    // 编译 .vue 文件
    else if (/\.vue$/.test(file)) {
      const source = fs.readFileSync(absolutePath, 'utf-8');
      fs.removeSync(absolutePath);

      const outputVuePath = absolutePath + '.js';
      const outputJsPath = absolutePath.replace('.vue', '.js');
      const output = fs.existsSync(outputJsPath) ? outputVuePath : outputJsPath;
      fs.outputFileSync(output, compiler(source));
    }
  });
}

function isDir(dir) {
  return fs.lstatSync(dir).isDirectory();
}


text:
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Endless Runner PixiJS</title>

		<link rel="stylesheet" href="../dist/endless-runner-pixijs.css">

        <script type="text/javascript" src="../bower_components/requirejs/require.js" data-main="../dist/endless-runner-pixijs.js"></script>
    </head>
    <body>

    </body>
</html>


text:
AUTO_TARBALL=1

include make/generic-rpm.make

test::
	nosetests

test-coverage::
	nosetests --with-coverage --cover-package latency


text:
package common;

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
public @interface Anno {
	String id();

	int someValue() default 37;

	long longValue() default 2L;
}


text:
package com.twitter.finagle.redis.protocol

import com.twitter.io.Buf

case object Discard extends Command {
  def name: Buf = Command.DISCARD
}

case object Exec extends Command {
  def name: Buf = Command.EXEC
}

case object Multi extends Command {
  def name: Buf = Command.MULTI
}

case object UnWatch extends Command {
  def name: Buf = Command.UNWATCH
}

case class Watch(keys: Seq[Buf]) extends KeysCommand {
  def name: Buf = Command.WATCH
  override def body: Seq[Buf] = keys
}
object Watch {
  def apply(args: => Seq[Array[Byte]]): Watch = new Watch(args.map(Buf.ByteArray.Owned(_)))
}


text:
module Saml
  module Config
    mattr_accessor :provider_type
    @@provider_type = "service_provider"

    mattr_accessor :max_issue_instant_offset
    @@max_issue_instant_offset = 2

    mattr_accessor :ssl_private_key
    @@ssl_private_key = nil

    mattr_accessor :ssl_certificate
    @@ssl_certificate = nil

    mattr_accessor :http_ca_file
    @@http_ca_file = nil

    mattr_accessor :registered_stores
    @@registered_stores = {}

    mattr_accessor :generate_key_name
    @@generate_key_name = true

    mattr_accessor :signature_algorithm
    @@signature_algorithm = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"

    mattr_accessor :digest_algorithm
    @@digest_algorithm = "http://www.w3.org/2001/04/xmlenc#sha256"

    mattr_accessor :default_store

    mattr_accessor :inclusive_namespaces_prefix_list
    @@inclusive_namespaces_prefix_list = "ds saml samlp xs"

    mattr_accessor :include_nested_prefixlist
    @@include_nested_prefixlist = false

    def register_store(name, store, options = {})
      registered_stores[name] = store
      self.default_store = name if options[:default]
    end
    module_function :register_store

    def ssl_private_key_file=(private_key_file)
      if private_key_file.present?
        self.ssl_private_key = OpenSSL::PKey::RSA.new File.read(private_key_file)
      else
        self.ssl_private_key = nil
      end
    end
    module_function :ssl_private_key_file=

    def ssl_certificate_file=(certificate_file)
      if certificate_file.present?
        self.ssl_certificate = OpenSSL::X509::Certificate.new File.read(certificate_file)
      else
        self.ssl_certificate = nil
      end
    end
    module_function :ssl_certificate_file=

  end
end


text:
<?php

declare(strict_types=1);

namespace ApiPlatform\Core\Tests\Bridge\Doctrine\MongoDbOdm\PropertyInfo\Fixtures;

/**
 * @author Teoh Han Hui <teohhanhui@gmail.com>
 */
class Foo
{
    /**
     * @var string
     */
    public $bar;
}


text:
---
layout: post
excerpt: Blog
title: 'Construtores em Java'
description: 'Descobre como se trabalha com construtores na linguagem de programação Java. Obtém respostas às tuas dúvidas com a teoria e os exemplos apresentados.'
keywords: 'java, construtores, construtor, publicação'
date: 2022-03-16
categories: [Java]
redirect_from:
  - /blog/20220316/construtores-em-java/
---

Nesta publicação aprende-se a trabalhar com construtores para que se possa usar esses mesmos conhecimentos e assim evoluir.

- os construtores têm como função inicializar tudo o que seja necessário ao se criar um determinado objeto;
- pode-se criar vários construtores numa classe.

```java
package com.caffeinealgorithm.programaremjava;

public class Main {
  public static void main(String[] args) {
    var pessoa1 = new Construtores("Nelson", "Silva", 25);
    var pessoa2 = new Construtores("Larissa", "Fernandes", 17);

    pessoa1.informacao();
    pessoa1.verificarEntrada();

    /*
      Nome: Nelson Silva
      Idade: 25
      Esta pessoa pode entrar no local porque tem mais de 18 anos.
    */

    pessoa2.informacao();
    pessoa2.verificarEntrada();

    /*
      Nome: Larissa Fernandes
      Idade: 17
      Esta pessoa não pode entrar no local porque tem menos de 18 anos.
    */
  }
}
```

```java
package com.caffeinealgorithm.programaremjava;

public class Construtores {
  String primeiroNome = null, ultimoNome = null;
  int idade = 0;

  public Construtores(String primeiroNome, String ultimoNome, int idade) {
    this.primeiroNome = primeiroNome;
    this.ultimoNome = ultimoNome;
    this.idade = idade;
  }

  public void informacao() {
    System.out.printf("Nome: %s %s\n", primeiroNome, ultimoNome);
    System.out.printf("Idade: %d\n", idade);
  }

  public void verificarEntrada() {
    if (idade >= 18)
      System.out.println("Esta pessoa pode entrar no local porque tem mais de 18 anos.");
    else
      System.out.println("Esta pessoa não pode entrar no local porque tem menos de 18 anos.");
  }
}
```

Não te esqueças de [assistir ao vídeo](https://youtu.be/vZjw1DbKVsY){:target="\_blank"} e podes sempre ler esta publicação [em inglês](https://nelsonsilvadev.com/blog/constructors-in-java/){:target="\_blank"}.

### _Happy coding!_


text:
namespace MoreDotNet.Wrappers
{
    public static class LongWarppers
    {
        public static decimal FromOaCurrency(this long input)
        {
            return decimal.FromOACurrency(input);
        }
    }
}


text:
package br.com.web.dao;

import java.util.List;

import br.com.web.model.Produto;

public interface ProdutoDao {

	public void adiciona(Produto produto);

	public List<Produto> getProdutos();

	public Produto getProduto(int id);

	public void altera(Produto produto);

	public void remove(int id);

	public void close();

	public List<Produto> getProdutosByClassificacao(String animal);
}


text:
The [Save to Google Pay button][save-to-google-pay] makes it easy embed the Save to Google Pay functionality into your
websites.

<img src="docs/images/save-to-google-pay-button.png" width="236" height="44" alt="Save to Google Pay" />

This repository takes the [Save to Google Pay button][save-to-google-pay] experience and makes the integration process
easier for those building websites with frameworks like React, Angular, Vue (and many others), or even those who don't
use a framework.

## Web component

[![npm version](https://badge.fury.io/js/%40google-pay%2Fsave-button-element.svg)][npm-element]

The [Save to Google Pay web component button][save-button-element] makes it easy to integrate the Save to Google Pay
button into your website using standards based custom elements. Web components can be used directly in a standard HTML
web application as is, and is also [compatible with many popular web frameworks][custom-elements-compatible].

```sh
npm install @google-pay/save-button-element
```

Find out more about the [Save to Google Pay web component button][save-button-element].

## React

[![npm version](https://badge.fury.io/js/%40google-pay%2Fsave-button-react.svg)][npm-react]

Web components are more difficult to consume in a React application due to the extra work involved in binding to web
component properties with React.

A separate [Save to Google Pay React button][save-button-react] as been created to make it just as easy to integrate the
Save to Google Pay button into your React website.

```sh
npm install @google-pay/save-button-react
```

Find out more about the [Save to Google Pay React button][save-button-react].

## Angular

[![npm version](https://badge.fury.io/js/%40google-pay%2Fsave-button-angular.svg)][npm-angular]

An Angular version of the [Save to Google Pay button][save-button-angular] as been created to make it just as easier to
integrate the Save to Google Pay button into your Angular website. The advantage of using the Angular version of the
Google Pay button over the web component is that it eliminates the need to register `CUSTOM_ELEMENTS_SCHEMA`.

```sh
npm install @google-pay/save-button-angular
```

Find out more about the [Save to Google Pay Angular button][save-button-angular].

## Other frameworks

The intention is for the web component to support other web frameworks. Support for additional framework specific
libraries will be considered based on demand.

## Have any questions?

Ask it on the [discussions](https://github.com/google-pay/save-to-google-pay-button/discussions) section of the Google
Pay button project.

[save-to-google-pay]: https://developers.google.com/pay/passes/reference/s2w-reference
[save-button-element]: src/save-button-element
[save-button-react]: src/save-button-react
[save-button-angular]: src/save-button-angular
[live-demo]: https://developers.google.com/pay/api/web/guides/resources/demos
[custom-elements-compatible]: https://custom-elements-everywhere.com/
[npm-element]: https://www.npmjs.com/package/@google-pay/save-button-element
[npm-react]: https://www.npmjs.com/package/@google-pay/save-button-react
[npm-angular]: https://www.npmjs.com/package/@google-pay/save-button-angular


text:
<%= question_subject %>

<%= question_lite %>

hover over a star for more info, click to select

Previous

Next


text:
@interface YPHomeDropdown : UIView

+ (instancetype)dropdown;

@end


text:
import { hashString, BinaryRepresentationForBarcodeData, Mod11, htmlString, Capitalize, AmountLocale, FormatDate } from './helper'
import { IBoleto, IOptions, IBank } from './interfaces'
import { Banks } from './banks'
import { GeneratePdf } from './pdf-layout'
import { merge } from 'ramda';
export const CreateBoleto = (options): IBoleto => {
	const bank: IBank = Banks[options.banco]
	let boleto: IBoleto = merge(options, {
		bank: bank,
		data_emissao: options.data_emissao || new Date(),
		data_vencimento: options.data_vencimento || new Date(new Date().getTime() + (5 * 24 * 3600 * 1000)),
		pagador: htmlString(options.pagador),
		instrucoes: htmlString(options.instrucoes),
		local_de_pagamento: options.local_de_pagamento || 'Até o vencimento, preferencialmente no Banco ' + Capitalize(options.banco),
		codigo_banco: bank.codigo + '-' + Mod11(bank.codigo),
		barcodeRenderEngine: 'img',
		nosso_numero_dv: Mod11(options.nosso_numero.toString()),
		barcode_data: null,
		linha_digitavel: null
	})
	const barcode_data = bank.barcodeData(boleto)
	const linhaDigitavel = bank.linhaDigitavel(barcode_data)
	boleto = merge(boleto, {
		barcode_data: barcode_data,
		linha_digitavel: linhaDigitavel,
		amount: AmountLocale(Number(options.valor)),
		data_emissao_formatted: FormatDate(boleto.data_emissao),
		data_vencimento_formatted: FormatDate(boleto.data_vencimento),
		renderOptions: {
			barcode_height: 50,
			barcode_data: BinaryRepresentationForBarcodeData(barcode_data),
			linha_digitavel_hash: hashString(linhaDigitavel).toString()
		},
	})
	boleto.pdf = GeneratePdf(boleto)
	return boleto
}

// Boleto.prototype.renderHTML = function(callback) {
// 	var self = this
//
// 	var renderOptions = self.bank.options
// 	renderOptions.boleto = self
//
// 	// Copy renderHelper's methods to renderOptions
// 	for (var key in formatters) {
// 		renderOptions[key] = formatters[key]
// 	}
//
// 	renderOptions['barcode_render_engine'] = Boleto.barcodeRenderEngine
// 	renderOptions['barcode_height'] = '50'
//
// 	if (Boleto.barcodeRenderEngine == 'bmp') {
// 		renderOptions['barcode_data'] = barcode.bmpLineForBarcodeData(self['barcode_data'])
// 	} else if (Boleto.barcodeRenderEngine == 'img') {
// 		renderOptions['barcode_data'] = barcode.binaryRepresentationForBarcodeData(self['barcode_data'])
// 	}
//
// 	renderOptions['boleto']['linha_digitavel_hash'] = hashString(renderOptions['boleto']['linha_digitavel']).toString()
//
// 	ejs.renderFile(path.join(__dirname, '/../assets/layout.ejs'), renderOptions, {
// 		cache: true
// 	}, function(err, html) {
// 		if (err) {
// 			throw new Error(err)
// 		}
//


text:
using System;

namespace Zenject.Asteroids
{
    public static class Signals
    {
        public class ShipCrashed : Signal
        {
            public class Trigger : TriggerBase
            {
            }
        }
    }
}


text:
package org.apache.drill.exec.oauth;

import java.util.Iterator;
import java.util.Map;

/**
 * Persistent Registry for OAuth Tokens
 */
public interface TokenRegistry extends AutoCloseable {

  /**
   * Creates a token table for specified {@code pluginName}.
   * @param pluginName The name of the plugin instance.
   */
  void createTokenTable(String pluginName);

  PersistentTokenTable getTokenTable(String name);

  /**
   * Deletes the token table for specified {@code pluginName}.
   * @param pluginName name of the plugin whose token table should be removed
   */
  void deleteTokenTable(String pluginName);

  /**
   * Returns iterator for aliases table entries.
   */
  Iterator<Map.Entry<String, Tokens>> getAllTokens();
}


text:
namespace chromeos {
class CrosSettings;
class DeviceSettingsService;
class SessionManagerClient;
}

namespace policy {

class CloudPolicyClient;
class DeviceLocalAccountPolicyStore;
class DeviceManagementService;

// The main switching central that downloads, caches, refreshes, etc. policy for
// a single device-local account.
class DeviceLocalAccountPolicyBroker {
 public:
  explicit DeviceLocalAccountPolicyBroker(
      const std::string& user_id,
      scoped_ptr<DeviceLocalAccountPolicyStore> store);
  ~DeviceLocalAccountPolicyBroker();

  const std::string& user_id() const { return user_id_; }

  CloudPolicyCore* core() { return &core_; }
  const CloudPolicyCore* core() const { return &core_; }

  // Establish a cloud connection for the service.
  void Connect(scoped_ptr<CloudPolicyClient> client);

  // Destroy the cloud connection, stopping policy refreshes.
  void Disconnect();

  // Reads the refresh delay from policy and configures the refresh scheduler.
  void UpdateRefreshDelay();

  // Retrieves the display name for the account as stored in policy. Returns an
  // empty string if the policy is not present.
  std::string GetDisplayName() const;

 private:
  const std::string user_id_;
  scoped_ptr<DeviceLocalAccountPolicyStore> store_;
  CloudPolicyCore core_;

  DISALLOW_COPY_AND_ASSIGN(DeviceLocalAccountPolicyBroker);
};

// Manages user policy blobs for device-local accounts present on the device.
// The actual policy blobs are brokered by session_manager (to prevent file
// manipulation), and we're making signature checks on the policy blobs to
// ensure they're issued by the device owner.
class DeviceLocalAccountPolicyService : public content::NotificationObserver,
                                        public CloudPolicyStore::Observer {
 public:
  // Interface for interested parties to observe policy changes.
  class Observer {
   public:
    virtual ~Observer() {}

    // Policy for the given |user_id| has changed.
    virtual void OnPolicyUpdated(const std::string& user_id) = 0;

    // The list of accounts has been updated.
    virtual void OnDeviceLocalAccountsChanged() = 0;
  };

  DeviceLocalAccountPolicyService(
      chromeos::SessionManagerClient* session_manager_client,
      chromeos::DeviceSettingsService* device_settings_service,
      chromeos::CrosSettings* cros_settings);
  virtual ~DeviceLocalAccountPolicyService();

  // Initializes the cloud policy service connection.
  void Connect(DeviceManagementService* device_management_service);

  // Prevents further policy fetches from the cloud.
  void Disconnect();

  // Get the policy broker for a given |user_id|. Returns NULL if that |user_id|
  // does not belong to an existing device-local account.
  DeviceLocalAccountPolicyBroker* GetBrokerForUser(const std::string& user_id);

  // Indicates whether policy has been successfully fetched for the given
  // |user_id|.
  bool IsPolicyAvailableForUser(const std::string& user_id);

  void AddObserver(Observer* observer);
  void RemoveObserver(Observer* observer);

  // NotificationObserver:
  virtual void Observe(int type,
                       const content::NotificationSource& source,
                       const content::NotificationDetails& details) OVERRIDE;

  // CloudPolicyStore::Observer:
  virtual void OnStoreLoaded(CloudPolicyStore* store) OVERRIDE;
  virtual void OnStoreError(CloudPolicyStore* store) OVERRIDE;

 private:
  struct PolicyBrokerWrapper {
    PolicyBrokerWrapper();

    // Return the |broker|, creating it first if necessary.
    DeviceLocalAccountPolicyBroker* GetBroker();

    // Fire up the cloud connection for fetching policy for the account from the
    // cloud if this is an enterprise-managed device.
    void ConnectIfPossible();

    // Destroy the cloud connection.
    void Disconnect();

    // Delete the broker.
    void DeleteBroker();

    std::string user_id;
    std::string account_id;
    DeviceLocalAccountPolicyService* parent;
    DeviceLocalAccountPolicyBroker* broker;
  };

  typedef std::map<std::string, PolicyBrokerWrapper> PolicyBrokerMap;

  // Re-queries the list of defined device-local accounts from device settings
  // and updates |policy_brokers_| to match that list.
  void UpdateAccountList();

  // Deletes brokers in |map| and clears it.
  void DeleteBrokers(PolicyBrokerMap* map);

  // Find the broker for a given |store|. Returns NULL if |store| is unknown.
  DeviceLocalAccountPolicyBroker* GetBrokerForStore(CloudPolicyStore* store);

  chromeos::SessionManagerClient* session_manager_client_;
  chromeos::DeviceSettingsService* device_settings_service_;
  chromeos::CrosSettings* cros_settings_;

  DeviceManagementService* device_management_service_;

  // The device-local account policy brokers, keyed by user ID.
  PolicyBrokerMap policy_brokers_;

  ObserverList<Observer, true> observers_;

  // Weak pointer factory for cros_settings_->PrepareTrustedValues() callbacks.
  base::WeakPtrFactory<DeviceLocalAccountPolicyService>
      cros_settings_callback_factory_;

  DISALLOW_COPY_AND_ASSIGN(DeviceLocalAccountPolicyService);
};

}  // namespace policy

#endif  // CHROME_BROWSER_CHROMEOS_POLICY_DEVICE_LOCAL_ACCOUNT_POLICY_SERVICE_H_


text:
(function(){
		var app = angular.module('recipeApp');

		app.filter('image', function(){

			return function(src){
				if(src){
					return `content/Images/food/${src}.jpg`;
				}
				return '';
			}

		});
})();


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="fr.bmartel.android.notti.service">

    <uses-permission android:name="android.permission.BLUETOOTH" />
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

    <uses-feature
        android:name="android.hardware.bluetooth_le"
        android:required="true" />

    <application
        android:allowBackup="true"
        android:label="@string/app_name">

        <service
            android:name=".NottiBtService"
            android:enabled="true">

            <intent-filter>
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>

        </service>

    </application>

</manifest>


text:
package io.quarkus.it.resteasy.jackson;

import static io.restassured.RestAssured.when;
import static org.hamcrest.Matchers.containsString;

import org.junit.jupiter.api.Test;

import io.quarkus.test.junit.QuarkusTest;

/**
 * This and {@link StaticContentWithTestProfileTest} don't really belong in this module,
 * but adding an extra Maven module just to introduce a test that uses a random http port seems
 * like overkill...
 */
@QuarkusTest
public class StaticContentTest {

    @Test
    public void testIndexHtml() {
        when().get("/index.html").then().statusCode(200).body(containsString("<title>Testing Guide</title>"));
    }
}


text:
<?php
class Catalog extends CI_Controller {
    public function Catalog() {
		parent::__construct();
		$this->load->model('Catalog_model');
		$this->load->model('Comments_model');
		$this->load->library('session');
    }

	public function index() {
		$this->load->helper('form');
		$pageData['meta_k'] = 'rpg maker, rpgmaker, rpg maker vx, rpgmakervx, rpg maker vx ace, rpgmakervxace, создание игр, игры, разработка игр, RPG игры, RPG, jRPG, скачать игры';
		$pageData['meta_d'] = 'RMaker - портал для разработчиков игр и игроков. Здесь можно разместить свою игру на RPG Maker или же скачать игру по нраву.';
		$pageData['title'] = 'RMaker — каталог игр — главная';
		$this->load->library('pagination');
		$config['base_url'] = base_url().'index.php/catalog/index';
		$this->db->like(array('approved'=>'1'));
		$this->db->from('games');
		$config['total_rows'] = $this->db->count_all_results();
		$config['per_page'] = 10;
		$config['use_page_numbers'] = TRUE;
		$page_num = $this->uri->segment(3, 1);
		$offset = ($page_num - 1) * $config['per_page'];
		$this->pagination->initialize($config);
		$pageData['pagination'] = $this->pagination->create_links();
		$pageData['games'] = $this->Catalog_model->getAllGames($config['per_page'], $offset);
		if ($pageData['games'] == false) {
			$pageData['errDescription'] = "Игр нет.";
		}
		$this->load->view('main', $pageData);
	}

	public function search() {
		$this->load->helper('form');
		$pageData['meta_k'] = 'rpg maker, rpgmaker, rpg maker vx, rpgmakervx, rpg maker vx ace, rpgmakervxace, создание игр, игры, разработка игр, RPG игры, RPG, jRPG, скачать игры';
		$pageData['meta_d'] = 'RMaker - портал для разработчиков игр и игроков. Здесь можно разместить свою игру на RPG Maker или же скачать игру по нраву.';
		$pageData['title'] = 'RMaker — каталог игр — поиск';

		//$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 1;

			$param = array(
				'title' => $this->input->post('title'),
				'author' => $this->input->post('author'),
				'status' => $this->input->post('status'),
				'maker' => $this->input->post('maker'),
				'genre' => $this->input->post('genre')['0'],
			);

		$pageData['games'] = $this->Catalog_model->getSearchGames($param);

		if ($pageData['games'] == false) {
			$pageData['errDescription'] = "Игр нет.";
		}
		$this->load->view('main', $pageData);
	}

	public function notappr() {
		$pageData['meta_k'] = 'rpg maker, rpgmaker, rpg maker vx, rpgmakervx, rpg maker vx ace, rpgmakervxace, создание игр, игры, разработка игр, RPG игры, RPG, jRPG, скачать игры';
		$pageData['meta_d'] = 'RMaker - портал для разработчиков игр и игроков. Здесь можно разместить свою игру на RPG Maker или же скачать игру по нраву.';
		$pageData['title'] = 'RMaker — каталог игр — неутвержденные';
		$this->load->library('pagination');
		$config['base_url'] = base_url().'index.php/catalog/notappr';
		$this->db->like(array('approved'=>'0'));
		$this->db->from('games');
		$config['total_rows'] = $this->db->count_all_results();
		$config['per_page'] = 10;
		$this->pagination->initialize($config);
		$pageData['pagination'] = $this->pagination->create_links();
		$pageData['games'] = $this->Catalog_model->notApproved($config['per_page'], $this->uri->segment(3));
		if ($pageData['games'] == false) {
			$pageData['errDescription'] = "Игр нет.";
		}
		$this->load->view('games/appg', $pageData);
	}

	public function gamedetails($gameid) {
		$pageData['game'] = $this->Catalog_model->getGameDetails($gameid);
		if ($pageData['game'] == false) {
			$pageData['errDescription'] = "Игры не существует.";
		}
		$pageData['title'] = 'RMaker — каталог игр — '.$pageData['game']['title'];
		$pageData['meta_k'] = 'rpg maker, rpgmaker, rpg maker vx, rpgmakervx, rpg maker vx ace, rpgmakervxace, создание игр, игры, разработка игр, RPG игры, RPG, jRPG, скачать игры';
		$pageData['meta_d'] = 'RMaker - портал для разработчиков игр и игроков. Здесь можно разместить свою игру на RPG Maker или же скачать игру по нраву.';
		$pageData['images_g'] = explode(', ', $pageData['game']['images']);
		if ($pageData['images_g']['0']==='') {
			$pageData['error']=true;
			$pageData['images_g'] = null;
		} else {
			$pageData['error']=false;
		}
		$this->load->helper('form');
		$pageData['comments'] = $this->Comments_model->getComments($gameid, 10, 0);
		$this->load->view("details", $pageData);
	}
	public function add() {
		if ( $this->ion_auth->logged_in() ) {
			$page['new']=true;
			$this->load->helper('form');
			$this->load->library('form_validation');
			$page['edit'] = array('title'=>'', 'annotation'=>'', 'id'=>'', 'status'=>'', 'maker'=>'', 'author'=>'', 'text_bb'=>'');
			$page['edit']['genre']=false;
			$this->form_validation->set_rules('title', 'Название', 'required');
			$this->form_validation->set_rules('annotation', 'Описание', 'required');
			$this->form_validation->set_rules('genre[]', 'Жанр', 'required');
			$this->form_validation->set_rules('maker[]', 'Движок', 'required');
			$this->form_validation->set_rules('status[]', 'Статус', 'required');
			$page['title'] = 'Rmaker — Игры — Добавление новой игры';
			$page['meta_k'] = 'rpg maker, rpgmaker, rpg maker vx, rpgmakervx, rpg maker vx ace, rpgmakervxace, создание игр, игры, разработка игр, RPG игры, RPG, jRPG, скачать игры';
			$page['meta_d'] = 'RMaker - портал для разработчиков игр и игроков. Здесь можно разместить свою игру на RPG Maker или же скачать игру по нраву.';
			if ($this->form_validation->run() === FALSE) {
				$page['success']=false;
				$this->load->view('games/edit', $page);
			} else {
				$this->Catalog_model->add();
				$page['success']=true;
				$this->load->view('games/edit', $page);
			}
		} else {
			redirect(base_url().'index.php/catalog');
		}
	}

	public function edit($gameid) {
		$game = $this->Catalog_model->getGameDetails($gameid);
		$user = $this->ion_auth->user()->row();
		if ($this->ion_auth->is_admin() || $game['author']=$user->username) {
			$pageData['new']=false;
			$pageData['edit'] = array('title'=>$game['title'], 'author'=>$game['author'], 'annotation'=>$game['annotation'], 'id'=>$game['id'], 'status'=>$game['status'], 'maker'=>$game['maker'], 'text_bb'=>$game['text_bb']);
			$pageData['edit']['genre']=explode(', ', $game['genre']);
			$this->load->helper('form');
			$this->load->library('form_validation');
			$this->form_validation->set_rules('title', 'Название', 'required');
			$this->form_validation->set_rules('annotation', 'Описание', 'required');
			$this->form_validation->set_rules('genre[]', 'Жанр', 'required');
			$this->form_validation->set_rules('maker[]', 'Движок', 'required');
			$this->form_validation->set_rules('status[]', 'Статус', 'required');
			$pageData['title'] = 'RMaker — каталог игр — Редактирование — '.$game['title'];
			$pageData['meta_k'] = 'rpg maker, rpgmaker, rpg maker vx, rpgmakervx, rpg maker vx ace, rpgmakervxace, создание игр, игры, разработка игр, RPG игры, RPG, jRPG, скачать игры';
			$pageData['meta_d'] = 'RMaker - портал для разработчиков игр и игроков. Здесь можно разместить свою игру на RPG Maker или же скачать игру по нраву.';
			if ($this->form_validation->run() === FALSE) {
				$pageData['success']=false;
				$game = $this->Catalog_model->getGameDetails($gameid);
				$pageData['edit'] = array('title'=>$game['title'], 'author'=>$game['author'], 'annotation'=>$game['annotation'], 'id'=>$game['id'], 'status'=>$game['status'], 'maker'=>$game['maker'], 'text_bb'=>$game['text_bb']);
				$pageData['edit']['genre']=explode(', ', $game['genre']);
				$this->load->view('games/edit', $pageData);
			} else {
				$pageData['success']=true;
				$this->Catalog_model->update($gameid);
				$pageData['info'] = $this->input->post('status');
				$game = $this->Catalog_model->getGameDetails($gameid);
				$pageData['edit'] = array('title'=>$game['title'], 'author'=>$game['author'], 'annotation'=>$game['annotation'], 'id'=>$game['id'], 'status'=>$game['status'], 'maker'=>$game['maker'], 'text_bb'=>$game['text_bb']);
				$pageData['edit']['genre']=explode(', ', $game['genre']);
				$this->load->view('games/edit', $pageData);
			}
		} else {
		redirect(base_url());
		}
	}
	public function delete($id) {
		$game = $this->Catalog_model->getGameDetails($id);
		$user = $this->ion_auth->user()->row();
		if ($this->ion_auth->is_admin() || $game['author']=$user->username) {
			if (!$game['file']=='') {
				unlink($game['file']);
			}
			$what = $this->Catalog_model->delete($id);
			if ($what) {
				redirect(base_url().'index.php/panel');
			}
		} else {
			redirect(base_url().'index.php/panel');
		}
	}

	public function upload($id) {
		$game = $this->Catalog_model->getGameDetails($id);
		$user = $this->ion_auth->user()->row();
		if ($this->ion_auth->is_admin() || $game['author']=$user->username) {
			$this->load->helper('form');
			$pageData['edit'] = array('title'=>$game['title'], 'annotation'=>$game['annotation'], 'id'=>$game['id'], 'status'=>$game['status'], 'maker'=>$game['maker'], 'file'=>$game['file']);
			$pageData['title'] = 'RMaker — каталог игр — Загрузка файла — '.$game['title'];
			$pageData['meta_k'] = 'rpg maker, rpgmaker, rpg maker vx, rpgmakervx, rpg maker vx ace, rpgmakervxace, создание игр, игры, разработка игр, RPG игры, RPG, jRPG, скачать игры';
			$pageData['meta_d'] = 'RMaker - портал для разработчиков игр и игроков. Здесь можно разместить свою игру на RPG Maker или же скачать игру по нраву.';
			$pageData['error'] = '';
			$path = './users/'.$game['author'].'/';
			if (!is_dir($path)) {
				mkdir($path, 0777, TRUE);
			}
			$config['upload_path'] = $path;
			$config['allowed_types'] = 'rar|zip';
			$config['encrypt_name'] = true;
			$this->load->library('upload', $config);
			if ( !$this->upload->do_upload()) {
				$pageData['error'] = $this->upload->display_errors();
				$this->load->view('games/upload', $pageData);
			} else {
				$pageData['error'] = array();
				$this->Catalog_model->upload($game['id'], $path.$this->upload->data()['file_name']);
				redirect(base_url().'index.php/catalog/upload/'.$game['id']);
			}
		}
	}

	public function approve($id) {
		if ($this->ion_auth->is_admin()) {
			$this->Catalog_model->approve($id);
			redirect(base_url().'index.php/catalog/gamedetailes/'.$id);
		} else {
			redirect(base_url().'index.php/catalog');
		}
	}

	public function delete_upload($id) {
		$game = $this->Catalog_model->getGameDetails($id);
		$user = $this->ion_auth->user()->row();
		if ($this->ion_auth->is_admin() || $game['author']=$user->username) {
			unlink($game['file']);
			$what = $this->Catalog_model->delete_upload($id);
			if ($what) {
				redirect(base_url().'index.php/catalog/upload/'.$game['id']);
			}
		} else {
			redirect(base_url().'index.php/panel');
		}
	}

	public function delete_image($id, $image) { // Test version
		$game = $this->Catalog_model->getGameDetails($id);
		$user = $this->ion_auth->user()->row();
		if ($this->ion_auth->is_admin() || $game['author']=$user->username) {
			$name = $game['author'];
			if (file_exists('users/'.$name.'/img/'.$image)) {
				unlink('users/'.$name.'/img/'.$image);
			}
			if (!(stripos($game['images'], 'users/'.$name.'/img/'.$image.', ')===false)) {
				$image = 'users/'.$name.'/img/'.$image.', ';
			} elseif (!(stripos($game['images'], ', users/'.$name.'/img/'.$image)===false)) {
				$image = ', users/'.$name.'/img/'.$image;
			} else {
				$image = 'users/'.$name.'/img/'.$image;
			}
			$what = $this->Catalog_model->delete_image($id, $image, $name);

			if ($what) {
				redirect(base_url().'index.php/catalog/upload_images/'.$game['id']);
			}
		} else {
			redirect(base_url().'index.php/catalog');
		}
	}

	public function upload_images($id) {
		$game = $this->Catalog_model->getGameDetails($id);
		$user = $this->ion_auth->user()->row();
		$string = '';
		//$pageData['images'] = null;
		if ($this->ion_auth->is_admin() || $game['author']=$user->username) {
			if ($this->input->post('load_files')) {
				$path = './users/'.$game['author'].'/img/';
				if (!is_dir($path)) {
					mkdir($path, 0777, TRUE);
				}
				$config['upload_path'] = $path;
				$config['allowed_types'] = 'jpg|png|gif';
				$config['max_size']	= '2048';
				$config['max_width'] = '1024';
				$config['max_height'] = '768';
				$config['encrypt_name'] = TRUE;
				$this->load->library('upload', $config);
				$this->upload->initialize($config);
				$temp_files = $_FILES;
				$count = count($_FILES['file']['name']);
				if ($count>0) {
				for ($i=0; $i<=$count-1; $i++)
					{
						$_FILES['file'] = array (
						'name'=>$temp_files['file']['name'][$i],
						'type'=>$temp_files['file']['type'][$i],
						'tmp_name'=>$temp_files['file']['tmp_name'][$i],
						'error'=>$temp_files['file']['error'][$i],
						'size'=>$temp_files['file']['size'][$i]);
						$this->upload->do_upload('file');
						$tmp_data = $this->upload->data();
						$files_data[$i]['data'] = $tmp_data['full_path'];
						$string = $string.stristr($tmp_data['full_path'], 'users/').', ';
					}
				}
				$string = substr($string, 0, -2);
				if ($game['images'] === null || $game['images'] === '') {
					$this->Catalog_model->upload_images($game['id'], $string);
				} else {
					$this->Catalog_model->update_images($game['id'], $string);
				}
				$game = $this->Catalog_model->getGameDetails($id);
			}
			$pageData['title'] = 'RMaker — каталог игр — Загрузка изображений — '.$game['title'];
			$pageData['images'] = explode(', ', $game['images']);
			if ($pageData['images']['0']==='') {
				$pageData['error']=true;
				$pageData['images'] = null;
			} else {
				$pageData['error']=false;
			}
			$pageData['meta_k'] = 'rpg maker, rpgmaker, rpg maker vx, rpgmakervx, rpg maker vx ace, rpgmakervxace, создание игр, игры, разработка игр, RPG игры, RPG, jRPG, скачать игры';
			$pageData['meta_d'] = 'RMaker - портал для разработчиков игр и игроков. Здесь можно разместить свою игру на RPG Maker или же скачать игру по нраву.';
			$game = $this->Catalog_model->getGameDetails($id);
			$pageData['game'] = $game;
			$this->load->view('games/images', $pageData);
		} else {
			redirect(base_url().'index.php/panel');
		}
	}

	public function download($id) {
		$this->load->helper('download');
		$this->load->helper('bbcode');
		$game = $this->Catalog_model->getGameDetails($id);
		$tmp_g = transliterate($game['title']);
		$file = $game['file'];
		$exp = explode('.', $file);
		$f_ext = end($exp);
		force_download($tmp_g.'.'.$f_ext, file_get_contents($file));
	}
}


text:
'use strict';

// Turns a string into slug form.
module.exports = function (string) {
  return string.toLowerCase().replace(/ /g,'-').replace(/[^\w-]+/g,'');
};


text:
package com.redhat.samples.ws;

import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.util.Set;

import javax.xml.namespace.QName;
import javax.xml.soap.SOAPMessage;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;

public class SoapXmlHandler implements SOAPHandler<SOAPMessageContext> {

  public static final String SOAP_XML = "com.redhat.samples.ws.SOAP_XML";

  @Override
  public boolean handleMessage(SOAPMessageContext context) {
    boolean outbound = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
    if (outbound) return true;

    SOAPMessage message = context.getMessage();
    OutputStream soapOut = new ByteArrayOutputStream();
    try {
      message.writeTo(soapOut);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
    context.put(SOAP_XML, soapOut.toString());
    context.setScope(SOAP_XML, MessageContext.Scope.APPLICATION);
    return true;
  }

  @Override
  public boolean handleFault(SOAPMessageContext context) {
    return true;
  }

  @Override
  public void close(MessageContext context) {}

  @Override
  public Set<QName> getHeaders() {
    return null;
  }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>DynamicLabel (Neo4j Community 2.0.0 API)</title>
<meta name="date" content="2013-12-08">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Neo4j Community

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.neo4j.graphdb

Class DynamicLabel

java.lang.Object

org.neo4j.graphdb.DynamicLabel

All Implemented Interfaces:

Label

public class DynamicLabel
extends Object
implements Label

A dynamically instantiated and named Label. This class is
 a convenience implementation of Label that is
 typically used when labels are created and named after a
 condition that can only be detected at runtime.

 For statically known labels please consider the enum approach as described
 in Label documentation.

See Also:

Label

Method Summary

Methods

Modifier and Type
Method and Description

boolean
equals(Object other)

int
hashCode()

static Label
label(String labelName)

String
name()

Returns the name of the label.

String
toString()

Methods inherited from class java.lang.Object

getClass, notify, notifyAll, wait, wait, wait

Method Detail

label

public static Label label(String labelName)

Parameters:

labelName - the name of the label.

Returns:

a Label instance for the given labelName.

name

public String name()

Description copied from interface: Label

Returns the name of the label. The name uniquely identifies a
 label, i.e. two different Label instances with different object identifiers
 (and possibly even different classes) are semantically equivalent if they
 have equal names.

Specified by:

name in interface Label

Returns:

the name of the label

toString

public String toString()

Overrides:

toString in class Object

equals

public boolean equals(Object other)

Overrides:

equals in class Object

hashCode

public int hashCode()

Overrides:

hashCode in class Object

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Neo4j Community

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Copyright © 2002–2013 The Neo4j Graph Database Project. All rights reserved.


text:
#region License Information
/*
 * This file is part of SimSharp which is licensed under the MIT license.
 * See the LICENSE file in the project root for more information.
 */
#endregion

namespace SimSharp {
  public interface IRandom {
    int Next();
    int Next(int upperBound);
    int Next(int lowerBound, int upperBound);
    double NextDouble();

    void Reinitialise(int seed);
  }
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package org.pieShare.pieShareAppFx.controller.api;

import java.io.IOException;
import javafx.fxml.Initializable;
import javafx.scene.Node;

/**
 *
 * @author Richard
 */
public interface IController extends Initializable {

	Node getControl() throws IOException;
}


text:
<resources>
    <!-- Default screen margins, per the Android Design guidelines. -->
    <dimen name="activity_horizontal_margin">16dp</dimen>
    <dimen name="activity_vertical_margin">16dp</dimen>
    <dimen name="fragment_horizontal_margin">8dp</dimen>
    <dimen name="fragment_vertical_margin">8dp</dimen>
    <dimen name="dialog_margin">8dp</dimen>
    <dimen name="padding_two">2dp</dimen>
    <dimen name="padding_four">4dp</dimen>
    <dimen name="padding_eight">8dp</dimen>
</resources>


text:
<!DOCTYPE html>

<meta http-equiv="content-type" content="text/html;charset=UTF-8" />

<meta charset="UTF-8" />
<title>JS SDK DOCUMENT - WeChat Official Account Admin Platform</title>
<meta name="generator" content="MediaWiki 1.17.0" />
<link rel="shortcut icon" href="http://admin.wechat.com/favicon.ico" />
<link rel="search" type="application/opensearchdescription+xml" href="opensearch_desc.php" title="WeChat Official Account Admin Platform (en)" />
<link rel="alternate" type="application/atom+xml" title="WeChat Official Account Admin Platform Atom feed" href="index890f.php?title=Special:RecentChanges&feed=atom" />
<link rel="stylesheet" href="loadeb8e.css?debug=false&lang=en&modules=mediawiki.legacy.commonPrint%2Cshared%7Cskins.vector&only=styles&skin=vector&*" />
<meta name="ResourceLoaderDynamicStyles" content="" />

JS SDK DOCUMENT
Back

From WeChat Official Account Admin Platform

					Jump to: navigation,
					search

Contents

1 Overview

1.1 Steps for Using the JS-SDK

1.1.1 Step 1: Binding Official Account to Domains

1.1.2 Step 2: Import the JS Library File

1.1.3 Step 3: Inject Correct Authentication Configuration via the config API

1.1.4 Step 4: Process the Successful Verification via the ready API

1.1.5 Step 5: Process the Failed Verification via the error API

1.2 Calling an API

2 Basic API

2.1 API for Determining Whether the Current Client Version Supports the Provided JS

3 Sharing API

3.1 API for Obtaining Share Status for "Share on Moments" and Customizing Sharing Contents

3.2 API for Obtaining Send Status for "Send to Chat" and Customizing Sharing Contents

4 Image API

4.1 API for Taking Photos or Choosing Images from the Mobile Phone Album

4.2 API for Previewing Images

4.3 API for Uploading Images

4.4 API for Downloading Images

5 Audio API

5.1 API for Starting Recording

5.2 API for Stopping Recording

5.3 API for Automatically Stopping Recording

5.4 API for Playing Voice Recording

5.5 API for Pausing Voice Recording

5.6 API for Stopping Voice Recording

5.7 API for Finishing Playing Voice Recording

5.8 API for Uploading Voice Recording

5.9 API for Downloading Voice Recording

6 Intelligent API

6.1 API for Voice Dictation and Returning Dictation Results

7 Equipment Information

7.1 API for Obtaining Network Status

8 Geographic Location

8.1 API for Viewing Location by Using the Built-in Map within WeChat

8.2 API for Obtaining Geographic Location

9 Interface Controls

9.1 API for Hiding the Top Right Menu

9.2 API for Displaying the Top Right Menu

9.3 API for Closing the Current Window

9.4 API for Hiding Menu Items in Batches

9.5 API for Displaying Menu Items within Sub-Menus

9.6 API for Hiding All Non-basic Menu Items

9.7 API for Displaying All Non-basic Menu Items

10 Scanning a QR Code

10.1 API for Scanning a QR Code

11 WeChat Coupons

11.1 Display a List of Store-Suitable Coupons and Obtaining the User's Selection

11.2 API for Adding Multiple Coupons

11.3 API for Viewing Coupons in WeChat Card Pack

12 Appendix 1: Signature Algorithm for the JS-SDK Using Rights

13 Appendix 2: List of All JS APIs

14 Appendix 3: List of All Menu Items

15 Appendix 4: Coupon Extension Field and Signature Generation Algorithm

16 Appendix 5: Common Errors and Solutions

17 Appendix 6: Sample Code

 Overview

WeChat JS-SDK (JavaScript SDK) is a WeChat-based web page development toolkit provided by the WeChat Official Account Admin Platform for web developers.

Through the WeChat JS-SDK, web developers can easily use native mobile features including taking photos, selecting images, recording voice and location from within WeChat. Developers may also provide WeChat users with a better web-based user experience by directly tapping into WeChat-specific features such as sharing, QR code scanning, coupons and payments.

This document describes how to use the WeChat JS-SDK and contains relevant precautions for web developers.

 Steps for Using the JS-SDK

 Step 1: Binding Official Account to Domains

An Official Account needs to be bound to pre-specified domains before using the WeChat JS-SDK. To do this, you're required to first write an email titled "Application to bind domains to the WeChat JS-SDK" to bd@wechat.com. The email should include the WeChat ID of your Official Account and domains that you would like to bind to the WeChat JS-SDK. Your domain must be a second-level domain or subdomain and you may provide up to 3 domain names. An example application email is provided below:

Subject: "Application to bind domains to the WeChat JS-SDK"

Message:

WeChat ID for Official Account: oa_test_wechatid

Domains: example.com, a.example.com, b.example.com

 Step 2: Import the JS Library File

Import the following JS library file in the page where the JS API is to be called (https supported): http://res.wx.qq.com/open/js/jweixin-1.0.0.js.

Note: AMD/CMD standard module loading methods are supported for loading the module.

 Step 3: Inject Correct Authentication Configuration via the config API

All pages requiring the JS-SDK must be injected with configuration information otherwise they cannot be called. A web page with a static URL only needs inject the configuration information once. However, a single page application (SPA) that dynamically changes it's URL  must inject updated configuration information each time the URL changes. At the current time, HTML5 pushState is not supported when injecting configuration information in the WeChat Android client. This issue will be corrected in Android version 6.2.

wx.config({
    debug: true, // Enables debugging mode. Return values of all APIs called will be shown on the client. To view the sent parameters, open the log view of developer tools on a computer browser. The parameter information can only be printed when viewed from a computer.
    appId: '', // Required, unique identifier of the official account
    timestamp: '', // Required, timestamp for the generated signature
    nonceStr: '', // Required, random string for the generated signature
    signature: '', // Required, signature. See Appendix 1.
    jsApiList: [] // Required, list of JS APIs to be used. See Appendix 2 for the list of all JS APIs
 });

 Step 4: Process the Successful Verification via the ready API

wx.ready(function(){
    // The callback function of ready API will be executed after a successful config authentication, and each API calling must be done after the config API obtains a result. As config is an asynchronous operation, all relevant API calling must be put in the callback function if it needs to be called while the page loads. A user-initiated API call can be called directly without needing to be put in the callback function.

});

 Step 5: Process the Failed Verification via the error API

wx.error(function(res){

    // The callback function of error API will be executed if config authentication fails. If authentication failure is due to an expired signature, the detailed error information can be viewed by enabling the debugging mode within config API, or via the returned res parameter. The signature can be updated here for the SPA.

});

 Calling an API

All APIs are called through the wx object (or jWeixin object). Parameters are placed in a variable of an JSON object type. In addition to parameters specific to each API type, there are also the following general parameters for all APIs:

success: indicates the callback function executed when the API call is successful

fail: indicates the callback function executed when the API call fails

complete: indicates the callback function executed when the API call has completed, no matter whether it succeeds or fails

cancel: indicates the callback function executed when a user clicks the cancel menu item, available for a those APIs having a user cancel  menu item

trigger: indicates the callback function when menu items are clicked, supporting only relevant APIs in menu items

Caution:Do not use asynchronous AJAX to update the sharing content in trigger callback function as sharing is a synchronous operation in the WeChat client and the response from the AJAX request in the current moment will not be returned.

All of the above functions are called with parameters placed in the object. In addition to data returned by specific to each API, there is a general parameter errMsg for all APIs. Its value has the following format:

Successful call: "xxx:ok", with xxx indicating the called API name

User cancelled: "xxx:cancel", with xxx indicating the called API name

Failed call: Contains specific error information

 Basic API

 API for Determining Whether the Current Client Version Supports the Provided JS

wx.checkJsApi({
    jsApiList: ['chooseImage'] // List of JS APIs to be checked. See Appendix 2 for the list of all JS APIs.
    success: function(res) {
        // Returned as key-value pairs, true for available API and false for unavailable API
        // Example: {"checkResult":{"chooseImage":true},"errMsg":"checkJsApi:ok"}
    });

Note: The checkJsApi is a reserved API newly introduced in WeChat client V6.0.2. The initial release of the developer APIs don't need to be checked via the checkJsApi API.

 Sharing API

Please note that violations including offering rewards to users for sharing content are prohibited. If any such violations are found, official account API access may be permanently revoked.

 API for Obtaining Share Status for "Share on Moments" and Customizing Sharing Contents

wx.onMenuShareTimeline({
    title: '', // Sharing title
    link: '', // Sharing link
    imgUrl: '', // Sharing image URL
    success: function () {
        // Callback function executed after a user confirms sharing
    },
    cancel: function () {
        // Callback function executed after a user cancels sharing
    }
});

 API for Obtaining Send Status for "Send to Chat" and Customizing Sharing Contents

wx.onMenuShareAppMessage({
    title: '', // Sharing title
    desc: '', // Sharing description
    link: '', // Sharing link
    imgUrl: '', // Sharing image URL
    type: '', // Sharing type, such as "music", "video " or "link". It is "link" by default.
    dataUrl: '', // The data URL should be provided for items of type "music" or "video". It is null by default.
    success: function () {
        // Callback function executed after a user confirms sharing
    },
    cancel: function () {
        // Callback function executed after a user cancels sharing
    }
});

 Image API

 API for Taking Photos or Choosing Images from the Mobile Phone Album

wx.chooseImage({
    success: function (res) {
        var localIds = res.localIds; // Local ID list of selected images. localIds can be used as the src attribute of the img tag to display images.
    }
});

 API for Previewing Images

wx.previewImage({
    current: '', // URL of the current image
    urls: [] // URL list of the images to be previewed
});

 API for Uploading Images

wx.uploadImage({
    localId: '', // Local ID of the image to be uploaded, obtained from the chooseImage API
    isShowProgressTips: 1, // 1 by default, which shows the progress tips
    success: function (res) {
        var serverId = res.serverId; // Server ID offor the uploaded returned image
    }
});

Note: The uploaded images will expire after 3 three days. Developers can download images to their own servers via the WeChat multimedia API. The serverId obtained here is media_id. Please refer to Transferring Multimedia Files. Calls to the multimedia file download API are currently limited to 10,000 calls per day. To increase the frequency, please write an email titled "Apply for Increase of Multimedia API Calling Limit" to open-weixin@qq.com, briefly describing your project, providing a link to the project, and explaining the projected user quantity and usage quantity.

 API for Downloading Images

wx.downloadImage({
    serverId: '', // Server ID of the image to be downloaded, obtained from the uploadImage API
    isShowProgressTips: 1, // 1 by default, which shows the progress tips
    success: function (res) {
        var localId = res.localId; // Local ID where the returnedof the downloaded image is downloaded
    }
});

 Audio API

 API for Starting Recording

wx.startRecord();

 API for Stopping Recording

wx.stopRecord({
    success: function (res) {
        var localId = res.localId;
    }
});

 API for Automatically Stopping Recording

wx.onVoiceRecordEnd({
    // The complete callback function will be executed if recording does not stop within 1 minute
    complete: function (res) {
        var localId = res.localId;
    }
});

 API for Playing Voice Recording

wx.playVoice({
    localId: '' // Local ID of the voice recording to be played, obtained from the stopRecord API
});

 API for Pausing Voice Recording

wx.pauseVoice({
    localId: '' // Local ID of the voice recording to be paused, obtained from the stopRecord API
});

 API for Stopping Voice Recording

wx.stopVoice({
    localId: '' // Local ID of the voice recording to be stopped, obtained from the stopRecord API
});

 API for Finishing Playing Voice Recording

wx.onVoicePlayEnd({
    success: function (res) {
        var localId = res.localId; // Local ID of the returned voice recording to be played
    }
});

 API for Uploading Voice Recording

wx.uploadVoice({
    localId: '', // Local ID of the voice recording to be uploaded, obtained from the stopRecord API
    isShowProgressTips: 1, // 1 by default, which shows the progress tips
        success: function (res) {
        var serverId = res.serverId; // Server ID of the returned uploaded voice recording
    }
});

Note: Uploaded voice recording will expire after 3three days. Developers can download voices to their own servers via the WeChat multimedia API. The serverId obtained here is media_id. Please refer to Transferring Multimedia Files. Calls to the multimedia file download API are currently limited to 10,000 calls per day. To increase the frequency, please write an email titled "Apply for Increase of Multimedia API Calling Limit" to open-weixin@qq.com, briefly describing your project, providing a link to the project, and explaining the projected user quantity and usage quantity.

 API for Downloading Voice Recording

wx.downloadVoice({
    serverId: '', // Server ID of the voice recording to be downloaded, obtained from the uploadVoice API
    isShowProgressTips: 1, // 1 by default, which shows the progress tips
    success: function (res) {
        var localId = res.localId; // Local ID of the downloaded voice
    }
});

 Intelligent API

 API for Voice Dictation and Returning Dictation Results

wx.translateVoice({
  localId: "", //Local ID of the voice recording to be recognized, obtained from the related recording API. Currently, only supports recognition of Mandarin Chinese
   isShowProgressTips: 1, // 1 by default, which shows the progress tips
   success: function (res) {
       alert(res.translateResult); // Voice dictation result
   }
});

 Equipment Information

 API for Obtaining Network Status

wx.getNetworkType({
    success: function (res) {
        var networkType = res.networkType; // Returns network type, including 2g, 3g, 4g and wifi
    }
});

 Geographic Location

 API for Viewing Location by Using the Built-in Map within WeChat

wx.openLocation({
    latitude: 0, // Latitude, floating number, between 90 and -90
    longitude: 0, // Longitude, floating number, between 180 and -180
    name: '', // Location name
    address: '', // Detailed description of address
    scale: 1, // Map scale level, integer value, between 1 and 28. It is the maximum value by default.
    infoUrl: '' // Hyperlink displayed at the bottom of the location viewing interface, which can be clicked to view the URL
});

 API for Obtaining Geographic Location

wx.getLocation({
    success: function (res) {
        var latitude = res.latitude; // Latitude, floating number, between 90 and -90
        var longitude = res.longitude; // Longitude, floating number, between 180 and -180
        var speed = res.speed; // Speed, Unit: m/s
        var accuracy = res.accuracy; // Location accuracy
    }
});

 Interface Controls

 API for Hiding the Top Right Menu

wx.hideOptionMenu();

 API for Displaying the Top Right Menu

wx.showOptionMenu();

 API for Closing the Current Window

wx.closeWindow();

 API for Hiding Menu Items in Batches

wx.hideMenuItems({
    menuList: [] // Menu items to be hidden. See Appendix 3 for a list of all menu items.
});

 API for Displaying Menu Items within Sub-Menus

wx.showMenuItems({
    menuList: [] // Menu items to be displayed. See Appendix 3 for a list of all menu items.
});

 API for Hiding All Non-basic Menu Items

wx.hideAllNonBaseMenuItem();

 API for Displaying All Non-basic Menu Items

wx.showAllNonBaseMenuItem();

 Scanning a QR Code

 API for Scanning a QR Code

wx.scanQRCode({
    desc: 'scanQRCode desc',
    needResult: 0, // 0 by default, with the scanning result processed by WeChat. The scanning result is directly returned if it is 1.
    scanType: ["qrCode","barCode"], // Scanning type, including QR code or bar code. Both by default.
    success: function (res) {
        var result = res.resultStr; // Scanning result when needResult is 1
    }
});

 WeChat Coupons

 Display a List of Store-Suitable Coupons and Obtaining the User's Selection

wx.chooseCard({
    shopId: '', // Store ID
    cardType: '', // Coupon type
    cardId: '', // Coupon ID
    timestamp: 0, // Signature's timestamp
    nonceStr: '', // Signature's random string
    signType: '', // Signature type, SHA1 by default
    cardSign: '', // Coupon signature. See Appendix 4 for details.
    success: function (res) {
        var cardList= res.cardList; // List of coupons selected by the user
    }
});

 API for Adding Multiple Coupons

wx.addCard({
    cardList: [{
        cardId: '',
        cardExt: ''
    }], // List of coupons to be added
    success: function (res) {
        var cardList = res.cardList; // List of added coupons
    }
});

 API for Viewing Coupons in WeChat Card Pack

wx.openCard({
    cardList: [{
        cardId: '',
        code: ''
    }]// List of coupons to be opened
});

 Appendix 1: Signature Algorithm for the JS-SDK Using Rights

jsapi_ticket

Developers must retrieve a jsapi_ticket, the temporary ticket for the official account to call the WeChat JS APIs, before generating a signature. By default, the jsapi_ticket will be valid for 2 hours (7,200 seconds), and can be obtained via access_token. As there is a cap to  the number of API calls made for obtaining a jsapi_ticket, refreshing jsapi_ticket too frequently will result in disabled access and potentially affect your access to the API. Therefore, developers should globally cache jsapi_ticket on their own servers.

Refer to the following document for obtaining access_token (validity period of 7,200 seconds; developers should globally cache access_token on their own servers):Access token.

Obtain jsapi_ticket via HTTP GET method by using the access_token obtained in step 1 (validity period of 7,200 seconds; developers should globally cache jsapi_ticket on their own servers):https://api.wechat.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi.

The following JSON is an example of a successful reply:

{
    "errcode":0,
    "errmsg":"ok",
    "ticket":"bxLdikRXVbTPdHSM05e5u5sUoXNKd8-41ZO3MhKoyN5OfkWITDGgnr2fwJ0m9E8NYzWKVZvdVtaUgWvsdshFKA",
    "expires_in":7200
}

After jsapi_ticket is obtained, signature for the JS-SDK API calls can be generated.

Signature Algorithm

Signature generating rules are as follows: Fields included in the signature include noncestr (random string), a valid jsapi_ticket and timestamp, and url (URL of the current web page, excluding the URL fragment identifier # and its following parts). After sorting all parameters used for signature in the ordered by each field names' ASCII code from small to large (lexicographical order), divide string1 into key-value pairs (key1=value1&key2=value2…). Note that all parameter names should be in lowercase. Apply SHA1 encryption on string1, adopting the original values of field name and field value without escaping the URL.

In short, signature=sha1(string1). Example:

noncestr=Wm3WZYTPz0wzccnW

jsapi_ticket=sM4AOVdWfPE4DxkXGEs8VMCPGGVi4C3VM0P37wVUCFvkVAy_90u5h9nbSlYy3-Sl-HhTdfl2fzFy1AOcHKP7qg

timestamp=1414587457

url=http://admin.wechat.com

Step 1: After sorting all parameters used for the signature by the ASCII codes of field name from small to large (lexicographical order), divide string1 into key-value pairs (key1=value1&key2=value2…):

jsapi_ticket=sM4AOVdWfPE4DxkXGEs8VMCPGGVi4C3VM0P37wVUCFvkVAy_90u5h9nbSlYy3-Sl-HhTdfl2fzFy1AOcHKP7qg&noncestr=Wm3WZYTPz0wzccnW&timestamp=1414587457&url=http://mp.weixin.qq.com

Step 2: Perform SHA1 encryption on string1 to obtain the signature:

f4d90daf4b3bca3078ab155816175ba34c443a7b

Caution:

The noncestr and timestamp parameters used for signature must be the same as those used  in wx.config API.

The url parameter used for signature must be the complete URL of the JS API calling page(excluding the URL fragment identifier # and its following parts).

For security considerations, developers must implement signature logic on their server.

Consult Appendix 5 if an error due to an invalid signature occurs.

 Appendix 2: List of All JS APIs

V1.0.0 APIs

onMenuShareTimeline

onMenuShareAppMessage

startRecord

stopRecord

onVoiceRecordEnd

playVoice

pauseVoice

stopVoice

onVoicePlayEnd

uploadVoice

downloadVoice

chooseImage

previewImage

uploadImage

downloadImage

translateVoice

getNetworkType

openLocation

getLocation

hideOptionMenu

showOptionMenu

hideMenuItems

showMenuItems

hideAllNonBaseMenuItem

showAllNonBaseMenuItem

closeWindow

scanQRCode

addCard

chooseCard

openCard

 Appendix 3: List of All Menu Items

Basic Menu

Report Abuse: "menuItem:exposeArticle"

Text Size: "menuItem:setFont"

Day Mode: "menuItem:dayMode"

Night Mode: "menuItem:nightMode"

Refresh: "menuItem:refresh"

View Official Account (Added): "menuItem:profile"

View Official Account (Non-added): "menuItem:addContact"

Share Menu

Send to Chat: "menuItem:share:appMessage"

Share on Moments: "menuItem:share:timeline"

Favorite: "menuItem:favorite"

Share on Facebook: "menuItem:share:facebook"

Secure Menu

Debug: "menuItem:jsDebug"

Edit Tag: "menuItem:editTag"

Delete: "menuItem:delete"

Copy URL: "menuItem:copyUrl"

Original Page: "menuItem:originPage"

Read Mode: "menuItem:readMode"

Open in Safari: "menuItem:openWithSafari"

Email: "menuItem:share:email"

Some Special Official Accounts: "menuItem:share:brand"

 Appendix 4: Coupon Extension Field and Signature Generation Algorithm

Description of Coupon Extension Field "cardExt"

As a JSON string, cardExt a JSON string providing unique information assigned by a merchant for a coupon. It includes the following fields:

Parameter

Required

Description

 code

 No

 A code specific to the instance of the coupon, which can be received only once. It is required when use_custom_code is set to true, otherwise not required.

 openid

 No

 OpenID of the specified recipient, which can only be received by that user. It is required for coupons with bind_openid being true, otherwise not required.

 timestamp

 Yes

 Timestamp, indicating the number of seconds since 00:00:00 of January 1st, 1970 to the current time as generated by the Vendor , and converted to a character string.

It is imported after being generated by the Vendor.

 signature

 Yes

 Signature, which is generated by the Vendor based on parameters in this table according to the specified SHA1 mode. For the specific signature scheme, see the following description. It is imported after being generated by the Vendor in compliance with specifications.

 balance

 No

 Lucky Money balance, in the unit of 0.01 yuan.The field is required for lucky money (LUCKY_MONEY) coupon types, otherwise not required.

Signature Description

Sort values of appsecret (unique certificate password of a third-party user), timestamp, card_id, code, openid and balance in lexicographical order.

Join character strings of all parameters in to one string, and then perform SHA1 encryption to obtain the signature.

Timestamp in the signature must be consistent with that in card_ext.

If code=23456, timestamp=141231233, card_id=345667, and appsecret=456789, then signature=sha1(14123123323456345667456789)=4F76593A4245644FAE4E1BC940F6422A0C3EC03E.

Description of Coupon Signature cardSign

Sort values of appsecret, app_id, location_id, times_tamp, nonce_str, card_id and card_type in lexicographical order.

Join character strings of all parameters in to one string, and then perform SHA1 encryption to obtain the cardSign.

 Appendix 5: Common Errors and Solutions

Using "debug: true" when calling the config API can enable debugging mode and alert error information on the page. Common errors and solutions are as follows:

Invalid url domain: The domain name of the current page is not bound to the used appid. (One appid can bind to three valid domain names. For details, see 1.1.1.)

Invalid signature: It is recommended to check the following in order:

Check whether the signature algorithm is correct.

Check whether nonceStr and timestamp in the config parameter are consistent with those used in the signature.

Check whether url is the complete URL of the page (with the wrong URL alerted), including query string parameters after '?' and excluding the URL fragment identifier '#' part.

Check whether appid in the config parameter is consistent with that used for obtaining jsapi_titicket.

Make sure that you have cached access_token and jsapi_ticket.

Make sure that the URL used for signature is dynamically generated, in other words, not hardcoded. For generating a dynamic url, refer to the implementation code  in PHP in the instance code. If a static html page transfers the URL from the client to the server for signature via AJAX, the client side needs to use JavaScript to obtain the URL of the current page excluding the URL fragment identifier '#' part (code example: location.href.split('#')[0]). Once the page is shared, the WeChat client will add other parameters to the end of the URL, in this case, If the current URL is not dynamically obtained, signature of the shared page will fail.

the permission value is offline verifying. This error is caused because config is not successfully executed, or the called JSAPI is not imported into the jsApiList parameter of config. It is recommended to check in the following order:

Check whether config is correctly executed.

If the  APIs are to be called once the page has completely loaded, they must be called in the callback function of wx.ready API.

Check whether the jsApiList parameter of config includes the APIs you have called.

Permission denied:. The official account has no rights to use this API. (Some APIs may only be used only after being given access right.)

The Android user has cancelled sharing on Moments, but a sharing success message is still returned. (The WeChat Team is aware of this problem and will be fixed in Android V6.1.)

Sharing fails on both iOS and Android systems. (Check whether the official account has been verified. Only the verified official accounts have the right to relevant sharing APIs. For verified official accounts, check whether the relevant share-listening APIs are triggered in the callback function of wx.ready API.)

Some Android V6.0.2 clients fail to use the share-listening API. (This problem does not apply to versions earlier than Android V6.0.2 or later than V6.0.2.58. Please download the latest version from weixin.qq.com.)

Developers fail to obtain jsapi_ticket after services go live, but the previous test succeeds. (Developers must cache access_token and jsapi_ticket on their own servers; otherwise, frequency cap will be triggered after services go live. Please be sure to cache the token and ticket to reduce redundant server requests, as this will avert a frequency cap and also speeds up your services. A frequency cap of 10,000 calls is currently provided to facilitate testing, and services will not be available once this limit is reached. Be sure to globally cache access_token and jsapi_ticket before services go live, both of which will be valid for 2 hours (7,200 seconds). Otherwise, services will not be available once the frequency cap is triggered.)

The API for uploading images is occasionally blocked in some Android versions. (This problem exists in Android V6.0.2, and it has been fixed in versions later than V6.0.2.58. Please download the latest version from the official website.)

How do you upload multiple images using uploadImage? (Image can only be uploaded one-at-a-time currently. To upload multiple images, call this API again after uploading the prior image.)

HttpGet in the sample code fails to support https. (This problem has been addressed on January 11, 2015. For the demo downloaded earlier than that day, please download the latest sample code.)

Image compression issue. The upload API in JS-SDK sets no limitation on the size of upload resources. (Compression support has been added to Android V6.0.2, and will be added to iOS V6.1.)

Locally selected images fail to be previewed. (No extra support is required because the chooseImage API supports preview.)

Invalid signature is displayed when jumping from URL a to URL b. (The URL used for generating the signature on the background is the current URL using JS-SDK, that is, URL b. Remember that the URL used for background signature must be the complete URL of the current page using JS-SDK excluding the URL fragment identifier '#' part.)

Are extra steps necessary for compatibility with earlier WeChat versions? (JS-SDK is compatible with earlier versions, without needing the developer to take extra steps. Note that some APIs newly introduced since V6.0.2 can only be called in later versions.)

config:fail. (This error is caused because the imported config parameter is incomplete. Make sure that appId, timestamp, nonceStr, signature, and jsApiList are correctly included.)

How do you download the multimedia resources uploaded to WeChat through the JS API to the developer's server? (Please see the remarks about uploadVoice and uploadImage in this document.)

The serverId that is uploaded through other devices can be successfully downloaded but fails to be played in Android. (This problem has been confirmed by WeChat Team and will be fixed in Android V6.1.)

Is the JS SDK available for subdomains whose parent domain has finished the binding? (Yes, it is fully available for the correct subdomains after their parent domain has finished the binding.)

Web page which is opened via Scanning QR Code in WeChat Android client will be closed after calling the scanQRCode API with scanning result returns directly. (This problem has been confirmed by WeChat Team and will be fixed in Android V6.1.)

External images outside WeChat Admin platform can not be shown in ios V6.1, but those from within WeChat Admin platform or WeChat server do not have this problem. (This problem has been confirmed by WeChat Team and will be fixed in ios V6.2.)

Multimedia resources uploaded from Android to WeChat server through JS -APISDK may have noises on the third-party server after being downloaded. (This problem has been confirmed by WeChat team and will be fixed.)

The JS APIs related to images and voices can only download the resources uploaded through JS API, but cannot download the resources uploaded through the multimedia background API. (This problem has been confirmed by WeChat team and will be fixed.)

Voice recording which is speex-filetype and uploaded via JS API can not be directly played in developer's page. (This problem has been confirmed by WeChat team and will be fixed. Developers can download the amr-filetype version to their own servers via the WeChat multimedia API.)

Injection will fail if developer use the pushState feature of HTML5 which is not yet supported in WeChat Android client and it will be fixed in Android V6.2.

 Appendix 6: Sample Code

Sample Code:

jssdk_sample.zip

Remark: Sample code implemented in PHP and provided for reference to developers. All developers must cache the retrieved access_token and jsapi_ticket to avoid frequency caps.

Retrieved from "http://admin.wechat.com/wiki/index.php?title=JS_SDK_DOCUMENT"

				<form class="searchform">
        <input type="text"   name="search" placeholder="Search Keywords [alt-s]" accesskey="s" class="searchform_text"/>
        <input type="submit" name="fulltext" value="Search" title="Get page with keywords" class="searchform_btn"/>
				</form>

New Developers Guide

Getting Started

Developers Requirements

Basic Support

Access Token

IP Address List

Return Codes

API Call Limits

Transferring Multimedia Files

Receiving Messages

Message Authentication

Common Messages

Event Messages

Speech Recognition Messages

Sending Messages

Callback Messages

Customer Service Messages

Advanced Broadcast Interface

User Management

Group Management API

Name Remarks

User Profile

Follower List

User Location

User Profile via Web

Network Status

User-defined Menu

Create

Query

Delete

Event

Promotion Support

Generating Parametric QR Code

URL Shortening API

Data Statistics

Followers Data

Rich Media Data

User-Sent Messages Data

Callback Data

Wechat JS-SDK

Wechat JS-SDK document

About Tencent |

 Service Terms |

Contact Us

Copyright © 2012-2015 Tencent. All Rights Reserved.


text:
/* -*- c++ -*- */
/*
 * Copyright 2016 <+YOU OR YOUR COMPANY+>.
 *
 * This is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3, or (at your option)
 * any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this software; see the file COPYING.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street,
 * Boston, MA 02110-1301, USA.
 */

#ifndef INCLUDED_AX25_PDU_PREPEND_APPEND_IMPL_H
#define INCLUDED_AX25_PDU_PREPEND_APPEND_IMPL_H

#include <ax25/pdu_prepend_append.h>

namespace gr {
  namespace ax25 {

    class pdu_prepend_append_impl : public pdu_prepend_append
    {
     private:
      int _prepend_length;
      int _append_length;
      uint8_t _fill_byte;

     public:
      pdu_prepend_append_impl(int prepend_length, int append_length, uint8_t fill_byte);
      ~pdu_prepend_append_impl();

      void output_frame(pmt::pmt_t input_pdu);

    };

  } // namespace ax25
} // namespace gr

#endif /* INCLUDED_AX25_PDU_PREPEND_APPEND_IMPL_H */


text:
/*
 Name, email, tripcode and staff title persistence and postform propagation
 */

let main = require('../main'),
	{$, $script, $email, $name, _, common, config} = main;

function load() {
	try {
		const id = JSON.parse(localStorage.ident);
		if (id.name)
			$name.val(id.name);
		if (id.email)
			$email.val(id.email);
	}
	catch(e) {}
}

let save = _.debounce(function() {
	try {
		const name = $name.val();
		let email = $email.val();
		// Staff login method
		if (email === config.LOGIN_KEYWORD) {
			$email.val('');
			$script('/ass/js/scripts/login.js');
			email = false;
		}

		if (name || email) {
			let id = {};
			if (name)
				id.name = name;
			if (email)
				id.email = email;
			localStorage.ident = JSON.stringify(id);
		}
		else
			localStorage.removeItem('ident');
	}
	catch(e) {}
}, 1000);

// Sync persistance and postForm with input changes
function propagate() {
	let postForm = main.request('postForm');
	if (postForm)
		postForm.renderIdentity();
	save();
}

main.defer(function() {
	load();
	$name.on('input', propagate);
	$email.on('input', propagate);
});


text:
require 'harvested'

module Harvest

  class InvoiceImport

    def self.run!
      new.run!
    end

    def run!
      message = []
      invoices.each do |harvest_invoice|
        if harvest_invoice.paid?
          invoice = ::Invoice.find_by_ref_nr(harvest_invoice.ref_nr)
          if invoice
            message << "Harvest invoice #{harvest_invoice.ref_nr} is already in the system."
          else
            message << "Importing invoice #{harvest_invoice.ref_nr} from Harvest."
            invoice = ::Invoice.create_from_harvest!(harvest_invoice)
          end
        end
      end
      puts message.join("\n")
      message
    end

    private

    def invoices
      @invoices ||= begin
        client = Harvest::ApiClient.instance
        client.invoices.all.map do |invoice|
          Harvest::InvoiceWrapper.new(invoice)
        end
      end
    end
  end
end


text:
/*global require, _ */
require.def('gma/utils/background',
    ['gma/base', 'gma/utils/render', 'gma/entities/shapes'],
    function(gma) {

        /** @module gma */

        /**
         * Provides some functions to transform specification into background
         * @class backgroundMaker
        */
        gma.backgroundMaker = function(spec) {

            var self = spec || {};

///////////////////////////////////////////////////////////////////////////////

/**
 * The z co-ordinate given to all background items
 * @property z
 * @type Number
*/
self.z = self.z || 0;

/**
 * Dispatcher for determining how to treat background specifications
 * @method process
 * @param manager {:api:`gma.manager`}
 * @param value {specification}
 * @return {:api:`gma.renderHelper`}
*/
self.process = self.process || function(manager, value) {
    if (value) {
        if (_.isString(value.config)) {
            func = self['process_' + value.config];
            if (_.isFunction(func)) {
                return func(manager, value, value.config);
            }
        }
        else if (_.isFunction(value.config)) {
            return value.config(manager, value);
        }

        //If we've made it this far, config is either unknown or undefined
        return self.process_other(manager, value, value.config);
    }
};

/**
 * Function to ensure value.entity is a rectangle
 * @method sanitise
 * @param value {specification}
 * @param opts {Options}
*/
self.sanitise = self.sanitise || function(value, opts) {
    opts = opts || {x:0, y:0, width:1, height:1};
    opts = _.extend(opts, value, value.entity)
    value.entity = gma.shapes.rectangle(opts)
};

/**
 * Processer for specifications with no or unknown type
 * @method process_other
 * @param manager {:api:`gma.manager`}
 * @param value {specification}
 * @param type {String}
 * @return {:api:`gma.renderHelper`}
*/
self.process_other = self.process_other || function(manager, value, type) {
    self.sanitise(value);
    var templateHelper = value.template || gma.unitCube;
    var box = templateHelper.getInstance();
    value._instance = box;
    return gma.renderHelper(value);
};

/**
 * Processer for skybox
 * @method process_skybox
 * @copy process_other
*/
self.process_skybox = self.process_skybox || function(manager, value, type) {
    if (!value.mesh) {
        value.mesh = gma.unitCubeInfo.mesh;
    }

    if (!value.texture && !value.material) {
        value.material = gma.unitCubeInfo.material;
    }

    if (value.texture && value.material) {
        delete value.material;
    }

    self.sanitise(value, {width:50, height:50, depth:1, x:0, y:0, z:-50})
    var box = gma.meshTemplate(value).getInstance();
    value._instance = box;
    return gma.renderHelper(value);
};

///////////////////////////////////////////////////////////////////////////////

            return self;

        };
    }
);